From a282b6f311cda1c53224c826d7a332d173eaac4e Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 16:53:15 -0800 Subject: [PATCH 001/224] The CrewAI Bot is a CrewAI conversational Agent The CrewAI engine was a one-step Flow that called the model through LiteLLM directly, so no CrewAI Agent ever ran. It now runs CrewAI 1.15.45's conversational Agent session, served by ag-ui-crewai with conversational=True, and keeps OpenBot's contract: - The server's system messages (the Bot's role and tool guidance), which ag-ui-crewai's conversational mode drops, reach the Agent after CrewAI's own system prompt. - OpenBot's tools are handed back to the server: each is a result_as_answer stand-in that ends the turn with the model's own call id, and its phantom backend tool events are suppressed. - Messages keep the ids they arrived with, so the authoritative snapshot doesn't show the thread twice. - An image on the request survives a continuation run. Same harness id, image, port and route; no API change. OpenAI, Anthropic and Google models go through CrewAI's native SDK clients (extras added); LiteLLM stays the fallback. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + agent-crewai/requirements.txt | 12 +- agent-crewai/src/main.py | 512 +++++++++++++++++++++++++------- agent-crewai/tests/test_main.py | 233 +++++++++------ docs/agent-frameworks.md | 14 + 5 files changed, 577 insertions(+), 200 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c48135468..214b4119a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **The CrewAI Bot is a CrewAI Agent.** A Bot on the CrewAI engine now answers through CrewAI's + conversational Agent (`Agent(conversational=True)`, new in CrewAI 1.15.45), served by + ag-ui-crewai's conversational mode. Before, it called the model directly from a one-step CrewAI + Flow. The Bot's role, the whole thread and OpenBot's tools reach it as they did, and its replies + still arrive whole rather than word by word. CrewAI now calls OpenAI, Anthropic and Google models + through their own SDKs, and calls any other model through LiteLLM as before. - **OpenBot Desktop on a Mac asks for your password only after you choose Continue.** When OpenBot installs the software it runs on, a card says your Mac will ask for your password and why, and macOS's prompt comes up only once you choose Continue. Before, the prompt came up by itself a diff --git a/agent-crewai/requirements.txt b/agent-crewai/requirements.txt index f089be47bb..58e75df500 100644 --- a/agent-crewai/requirements.txt +++ b/agent-crewai/requirements.txt @@ -1,4 +1,12 @@ -ag-ui-crewai +# The Bot is a conversational CrewAI Agent (`Agent(conversational=True)`'s Flow session), which +# CrewAI shipped in 1.15.45, and ag-ui-crewai serves it with `conversational=True`, which 1.0.0 has. +# Floors, not pins: CI installs these the way the image does, so a new release upstream is tested +# before it ships. +# +# The extras are CrewAI's own clients for the providers OpenBot offers. CrewAI calls a model it +# knows through the provider's SDK and refuses to start without it, even with LiteLLM installed. +crewai[anthropic,google-genai]>=1.15.45 +ag-ui-crewai>=1.0.0 uvicorn[standard] # litellm 1.106.0 imports `CacheableResult` from `mcp.types`, which exists only in mcp 2.x, while # ag-ui-crewai 1.0.0 requires mcp<2. The two cannot both be satisfied, so every CrewAI run failed @@ -8,4 +16,6 @@ uvicorn[standard] # Held here rather than raising mcp, because mcp>=2 is only reachable by letting the resolver walk # ag-ui-crewai back to 0.3.1 and crewai to 1.6.1. 1.105.1 does not reference the symbol at all and # leaves every other version exactly where it was. Lift this when ag-ui-crewai supports mcp 2. +# +# Still installed: CrewAI calls a model through LiteLLM when no provider SDK of its own knows it. litellm<1.106.0 diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 943970295b..67ead52f2b 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -1,20 +1,44 @@ -"""CrewAI as a Bot. - -The third harness in the box, and the first built the way every one after it will be: the AG-UI -integration that CrewAI's own ecosystem publishes, mounted on FastAPI, with nothing of the protocol -written here: we do not write adapters. This one imports `ag_ui_crewai` and stops. - -The contract with the rest of OpenBot is the same one the other Bots meet, and it is small: -serve AG-UI on a port, answer `/health`, and refuse anybody who does not carry the server's token. +"""CrewAI as a Bot: a conversational CrewAI Agent, served over AG-UI. + +The Bot is a real `crewai.Agent`, run the way CrewAI runs one in a chat session: a conversational +Flow (`conversational=True`, a `converse` route, `stream_turn`) whose one handler gives the +conversation to the Agent and appends its reply. That is the same bridge CrewAI builds for +`Agent(conversational=True).as_flow()` (see `crewai.agent.conversation`), and `ag_ui_crewai` +serves it with `add_crewai_flow_fastapi_endpoint(..., conversational=True)`, which maps AG-UI's +`threadId` to CrewAI's session and runs the turn through `stream_turn`. Nothing of the protocol is +written here. + +Three things OpenBot needs that CrewAI's own bridge does not do, and that this file adds: + +- THE BOT'S ROLE. The server sends its instructions as system messages, and the conversational + path drops system messages before the Flow sees them. They are kept aside here and given to the + Agent as system messages, right after CrewAI's own system prompt. +- THE WHOLE THREAD, EVERY RUN. A CrewAI session keeps its history in memory; OpenBot's server + sends the whole thread on every run, and a fresh process must answer from it. ag-ui-crewai seeds + the session from the run's messages, and the Agent is built anew for each turn, so nothing + depends on an earlier run having happened in this process. +- THE CALLER'S TOOLS ARE HANDED BACK. A CrewAI Agent runs its tools itself. OpenBot's tools are + run by the server: the Bot asks for one, the run ends, and the next run carries the result. Each + AG-UI tool becomes a CrewAI tool that records the call and ends the turn, and the turn's reply + is then the assistant message that asks for it. + +The contract with the rest of OpenBot is the one every Bot meets: serve AG-UI on a port, answer +`/health`, and refuse anybody who does not carry the server's token. """ +from __future__ import annotations + import hmac +import json import os import sys -from collections.abc import Mapping +import threading +from collections.abc import Iterator +from contextlib import contextmanager from copy import deepcopy from pathlib import Path -from typing import Any +from typing import Any, ClassVar +from uuid import uuid4 # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. @@ -25,104 +49,72 @@ import ag_ui_crewai.endpoint as crewai_endpoint from ag_ui.core import Message, Tool from ag_ui_crewai import add_crewai_flow_fastapi_endpoint -from crewai.flow.flow import Flow, listen, start +from crewai import LLM, Agent +from crewai.agent.conversation import AgentConversationState +from crewai.flow import ConversationConfig, Flow, listen +from crewai.flow.conversational import ConversationMessage +from crewai.tools import BaseTool +from crewai.utilities.pydantic_schema_utils import create_model_from_schema from fastapi import FastAPI, Request from fastapi.responses import JSONResponse -from litellm import acompletion +from pydantic import BaseModel, Field, PrivateAttr, field_validator # The one header OpenBot's server sends when it calls a managed Bot. Same name the TypeScript Bots # check, because a Bot is a Bot whatever it is written in. TOKEN_HEADER = "x-openbot-agent-token" +# Where the run's system messages and tools wait for the turn, in the Flow's state. Not names a +# CrewAI or AG-UI key uses, so neither ever reads or overwrites them. +INSTRUCTIONS_KEY = "openbot_instructions" +CALLER_TOOLS_KEY = "openbot_caller_tools" + +# What the Bot is to CrewAI. CrewAI opens its system prompt with "You are {role}. {backstory}" and +# the goal; these say only that the server's instructions, sent right after, are who it is. +ROLE = "the assistant your instructions describe" +BACKSTORY = "Your instructions follow, and they take precedence." +GOAL = "Help the person you are talking to, following your instructions." + def _expected_token() -> str: return (os.environ.get("MANAGED_AGENT_TOKEN") or "").strip() def _model() -> str: - """The provider and model OpenBot chose, in the form litellm wants. + """The provider and model OpenBot chose, in the form CrewAI's `LLM` wants. - `BOT_PROVIDER` and `BOT_MODEL` are set by the shell from the model screen. litellm addresses a - model as `provider/model`, and it reads that provider's key from the environment itself, which - is why nothing here touches a key. + `BOT_PROVIDER` and `BOT_MODEL` are set by the shell from the model screen. CrewAI addresses a + model as `provider/model`, and reads that provider's key and base URL from the environment + itself, which is why nothing here touches a key. - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already + The model half is whatever the endpoint publishes, slashes included. The first path component + is taken as the provider and the rest is sent as the model name, so a name that already contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. + and the call then either went to a provider nobody configured or sent only the second half to + the endpoint. """ settings = bot_settings("agent-crewai") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" - - -_PROVIDER_MESSAGE_FIELDS = { - "developer": {"role", "content", "name"}, - "system": {"role", "content", "name"}, - "user": {"role", "content", "name"}, - "assistant": { - "role", - "audio", - "content", - "function_call", - "name", - "refusal", - "tool_calls", - }, - "tool": {"role", "content", "tool_call_id"}, -} + return f"{settings.provider}/{settings.model}" -def _message_dict(message: Any) -> dict[str, Any]: - if isinstance(message, Mapping): - return dict(message) - return message.model_dump() +def _llm() -> LLM: + return LLM(model=_model()) -def _strip_none(message: dict[str, Any]) -> dict[str, Any]: - return {key: value for key, value in message.items() if value is not None} +# --- The run's system messages, kept for the Agent -------------------------------------------- -def _provider_tool_calls(tool_calls: Any) -> Any: - if not isinstance(tool_calls, list): - return deepcopy(tool_calls) - projected = [] - for tool_call in tool_calls: - if not isinstance(tool_call, Mapping): - tool_call = tool_call.model_dump() - projected.append( - _strip_none( - { - key: deepcopy(tool_call[key]) - for key in ("id", "type", "function") - if key in tool_call - } - ) +def _text(content: Any) -> str: + if isinstance(content, str): + return content + if isinstance(content, list): + return "\n".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and part.get("type") == "text" ) - return projected - - -def _provider_messages(messages: list[Any]) -> list[dict[str, Any]]: - """Project AG-UI state messages to provider chat fields without mutating state.""" - provider_messages = [] - for message in messages: - message_dict = _message_dict(message) - allowed_fields = _PROVIDER_MESSAGE_FIELDS.get(message_dict.get("role")) - if allowed_fields is None: - continue - projected = { - key: deepcopy(value) - for key, value in message_dict.items() - if key in allowed_fields - } - if "tool_calls" in projected: - projected["tool_calls"] = _provider_tool_calls(projected["tool_calls"]) - provider_messages.append(_strip_none(projected)) - return provider_messages + return "" _prepare_crewai_inputs = crewai_endpoint.crewai_prepare_inputs @@ -136,6 +128,12 @@ def _openbot_prepare_crewai_inputs( context: list[Any] | None = None, forwarded_props: Any = None, ): + """ag-ui-crewai's inputs, plus every system message of the run and its tools, set aside. + + The conversational path seeds the session with the run's messages less every system message, + and the server's are the Bot's role and the guidance for the tools it holds. They are kept + under a key of their own here, in order, and the turn hands them to the Agent. + """ inputs = _prepare_crewai_inputs( state=state, messages=messages, @@ -143,37 +141,345 @@ def _openbot_prepare_crewai_inputs( context=context, forwarded_props=forwarded_props, ) - if messages and getattr(messages[0], "role", None) == "system": - prepared_messages = inputs.get("messages") - if isinstance(prepared_messages, list): - leading_system = messages[0].model_dump() - if prepared_messages[:1] != [leading_system]: - inputs["messages"] = [leading_system, *prepared_messages] + inputs[INSTRUCTIONS_KEY] = [ + text + for message in messages + if getattr(message, "role", None) in ("system", "developer") + and (text := _text(getattr(message, "content", None)).strip()) + ] + inputs[CALLER_TOOLS_KEY] = [tool.model_dump() for tool in tools] return inputs crewai_endpoint.crewai_prepare_inputs = _openbot_prepare_crewai_inputs -class OpenBotFlow(Flow): - """A crew of one, which is the right size for a Bot answering a person. +# --- The caller's tools, handed back ---------------------------------------------------------- + + +class HandBack: + """Which of the caller's tools the Agent called in one turn, for the server to run. + + One per turn, never shared. The lock is for the Agent calling more than one tool at once, + which CrewAI runs on a pool. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self.names: list[str] = [] + + def record(self, name: str) -> None: + with self._lock: + self.names.append(name) + + def calls(self, messages: list[Any], names: dict[str, str]) -> list[dict[str, Any]]: + """The calls to hand back, as the model made them: its own ids and arguments. + + The model's call id, not one made up here, because the next run carries the tool's result + under that id and CrewAI sends it to the model with the call it answers. `names` maps the + name the model was shown to the name the server knows. + """ + if not self.names: + return [] + asked = next( + ( + message.get("tool_calls") + for message in reversed(messages) + if isinstance(message, dict) + and message.get("role") == "assistant" + and message.get("tool_calls") + ), + None, + ) or [] + handed_back = [] + for call in asked: + function = call.get("function") or {} + name = names.get(function.get("name")) + if name is None: + continue + arguments = function.get("arguments") + handed_back.append( + { + "id": call.get("id") or f"call_{uuid4().hex}", + "type": "function", + "function": { + "name": name, + "arguments": arguments + if isinstance(arguments, str) + else json.dumps(arguments or {}), + }, + } + ) + return handed_back + - CrewAI's own examples build multi-agent crews, and a person who wants that edits this. What - ships has to answer the first question somebody asks it without a role, a goal and a backstory - being invented on their behalf. +class CallerTool(BaseTool): + """An AG-UI tool, as a CrewAI tool that is not run here. + + Calling it records the call and ends the turn (`result_as_answer`), so the Agent never sees a + result it would have to invent. The server runs the tool, and the next run carries the result + in the thread like any other tool message. """ - @start() - async def answer(self): - messages = self.state.get("messages", []) - response = await acompletion( - model=_model(), - messages=_provider_messages(messages), - tools=self.state.get("tools") or None, - stream=False, + result_as_answer: bool = True + _hand_back: HandBack = PrivateAttr() + caller_name: str + + def __init__(self, *, hand_back: HandBack, **data: Any) -> None: + # The name the server knows it by, whatever CrewAI makes of `name` for the model. + super().__init__(caller_name=data["name"], **data) + self._hand_back = hand_back + + def _run(self, **arguments: Any) -> str: + self._hand_back.record(self.caller_name) + return "Handed to the caller to run." + + +# CrewAI reports every tool it runs, and ag-ui-crewai turns that report into a tool call with its +# result. For a caller's tool that is a call already "answered" (by the stand-in above), under an id +# the model never made, next to the real one the turn hands back: the server would store a phantom +# call and a result for it, and the provider would be sent an orphaned tool result on the next run. +# So a report of a caller's tool, by the Agent of a turn in progress, is not passed on. Any other +# tool an Agent here is given (one a person adds to this file) is reported as before. +_caller_tools_by_agent: dict[str, frozenset[str]] = {} +_caller_tools_lock = threading.Lock() +_is_backend_tool_event = crewai_endpoint.is_backend_tool_event + + +def _is_caller_tool_event(event: Any) -> bool: + with _caller_tools_lock: + names = _caller_tools_by_agent.get(str(getattr(event, "agent_id", None))) + return bool(names) and getattr(event, "tool_name", None) in names + + +def _reported_backend_tool_event(event: Any) -> bool: + return _is_backend_tool_event(event) and not _is_caller_tool_event(event) + + +crewai_endpoint.is_backend_tool_event = _reported_backend_tool_event + + +@contextmanager +def _handing_back(agent: Agent, tools: list[CallerTool]) -> Iterator[None]: + """While the Agent's turn runs, its reports of these tools stay here.""" + key = str(agent.id) + with _caller_tools_lock: + _caller_tools_by_agent[key] = frozenset( + name for tool in tools for name in (tool.name, tool.caller_name) + ) + try: + yield + finally: + with _caller_tools_lock: + _caller_tools_by_agent.pop(key, None) + + +def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[CallerTool]: + built: list[CallerTool] = [] + for tool in tools: + name = tool.get("name") + if not isinstance(name, str) or not name: + continue + parameters = tool.get("parameters") or {"type": "object", "properties": {}} + built.append( + CallerTool( + hand_back=hand_back, + name=name, + description=tool.get("description") or name, + args_schema=create_model_from_schema( + {"title": f"{name}_arguments", **parameters} + ), + ) + ) + return built + + +# --- The conversation ------------------------------------------------------------------------- + + +# What a provider accepts on each message, and on each tool call. AG-UI messages carry more (ids, +# metadata, encrypted values), CrewAI's session adds its own, and a strict provider refuses a +# request with a field it does not know rather than ignoring it. +_MESSAGE_FIELDS = { + "user": {"role", "content", "name", "files"}, + "assistant": {"role", "content", "name", "tool_calls"}, + "tool": {"role", "content", "name", "tool_call_id"}, +} +_TOOL_CALL_FIELDS = ("id", "type", "function") + + +def _message_dict(message: Any) -> dict[str, Any] | None: + """A session message as CrewAI's `kickoff` takes it, or None for one that is not a turn. + + The session holds `ConversationMessage` models, except the turn's own user message, which + CrewAI appends as a plain dict. System messages are not turns: the run's are handed to the + Agent separately, ahead of the conversation. + """ + if isinstance(message, BaseModel): + message = message.model_dump(exclude_unset=True) + allowed = _MESSAGE_FIELDS.get(message.get("role")) + if allowed is None: + return None + kept = { + key: deepcopy(value) + for key, value in message.items() + if key in allowed and value is not None + } + if isinstance(kept.get("tool_calls"), list): + kept["tool_calls"] = [ + {key: call[key] for key in _TOOL_CALL_FIELDS if key in call} + for call in kept["tool_calls"] + if isinstance(call, dict) + ] + # `content` stays even when empty: CrewAI requires it, and a message that only calls tools + # has none. + kept.setdefault("content", None) + return kept + + +class OpenBotConversationMessage(ConversationMessage): + """CrewAI's session message, with the AG-UI id it arrived under. + + ag-ui-crewai builds every MESSAGES_SNAPSHOT from the session and keeps a message's `id` when it + has one; CrewAI's own message has none, so every earlier message of the thread would come back + under a new id. A snapshot is authoritative (entries it repeats replace the client's copies), + and a whole thread under new ids is a thread shown twice. + """ + + id: str | None = None + + +class OpenBotConversationState(AgentConversationState): + messages: list[OpenBotConversationMessage] = Field(default_factory=list) + openbot_instructions: list[str] = Field(default_factory=list) + openbot_caller_tools: list[dict[str, Any]] = Field(default_factory=list) + + @field_validator("messages", mode="before") + @classmethod + def content_may_be_empty(cls, value: Any) -> Any: + """An assistant message that only calls tools has no content, and AG-UI leaves it out. + + CrewAI's session message requires the field, so the thread's tool calls would refuse the + whole run on the turn after the server ran a tool. + """ + if isinstance(value, list): + return [ + {**message, "content": None} + if isinstance(message, dict) and "content" not in message + else message + for message in value + ] + return value + + +def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The newest user message's pictures and files, kept as a message of their own. + + CrewAI makes the newest user message the turn's request and keeps only its text; every other + message goes to the model whole. ag-ui-crewai already splits a run that ends on the person's + message this way. A run that ends on a tool's result (the server ran a tool and the Bot + continues) does not get that split, so it is made here: the media just before the request, as + the person sent it. + """ + for index in range(len(conversation) - 1, -1, -1): + message = conversation[index] + if message.get("role") != "user": + continue + content = message.get("content") + if not isinstance(content, list): + return conversation + text = [part for part in content if isinstance(part, dict) and part.get("type") == "text"] + media = [part for part in content if not (isinstance(part, dict) and part.get("type") == "text")] + if not media: + return conversation + return [ + *conversation[:index], + {**message, "content": media}, + {**message, "content": "\n".join(part.get("text", "") for part in text)}, + *conversation[index + 1 :], + ] + return conversation + + +def _agent(tools: list[CallerTool]) -> Agent: + """The Bot, as a CrewAI Agent, for one turn. + + Its role, goal and backstory defer to the server's instructions, which follow CrewAI's own + system prompt as system messages of their own: they already say who the Bot is, and a role + invented here would only compete with them. + """ + return Agent( + role=ROLE, + goal=GOAL, + backstory=BACKSTORY, + llm=_llm(), + tools=tools, + allow_delegation=False, + verbose=False, + ) + + +class OpenBotAgentFlow(Flow[OpenBotConversationState]): + """The Agent's conversational session, the shape CrewAI gives `Agent(conversational=True)`. + + Every turn takes the `converse` route; there is nothing to route between. The Agent is built + for the turn from the run's own instructions and tools, so two Bots, or two runs of one, never + share one. + """ + + _standalone_agent: ClassVar[bool] = True + conversational: ClassVar[bool] = True + conversational_config: ClassVar[ConversationConfig] = ConversationConfig( + defer_trace_finalization=False + ) + _skip_auto_memory = True + + def route_turn(self, context: dict[str, Any]) -> str: + return "converse" + + @listen("converse") + async def converse_turn(self): + instructions = [ + {"role": "system", "content": text} for text in self.state.openbot_instructions + ] + conversation = [ + message + for message in map(_message_dict, self.state.messages) + if message is not None + ] + if not conversation: + raise ValueError("A turn needs at least one message") + conversation = _with_request_media(conversation) + hand_back = HandBack() + tools = _caller_tools(self.state.openbot_caller_tools, hand_back) + agent = _agent(tools) + with self._conversation_streaming_enabled(agent.llm), _handing_back(agent, tools): + # CrewAI keeps every message before the newest user message as history, with its + # role, after its own system prompt: the server's instructions lead it. + result = await agent.kickoff_async(messages=[*instructions, *conversation]) + calls = hand_back.calls( + result.messages, {tool.name: tool.caller_name for tool in tools} + ) + if calls: + # The turn's reply asks the caller to run its tools, and the run ends there. + self._reply(None, tool_calls=calls) + return None + self._reply(result.raw) + return result + + def _reply(self, content: str | None, **fields: Any) -> None: + """The turn's reply, appended the way `append_assistant_message` does, with an id. + + One id for the run, so every snapshot the run sends after it agrees on which message it is. + """ + object.__setattr__(self, "_assistant_reply_appended", True) + self.state.messages.append( + OpenBotConversationMessage( + id=str(uuid4()), role="assistant", content=content, **fields + ) ) - self.state.setdefault("messages", []).append( - response.choices[0].message.model_dump() + self._emit_conversation_message_added( + role="assistant", content=content, message_index=len(self.state.messages) - 1 ) @@ -204,4 +510,4 @@ async def health(): return {"ok": True, "harness": "crewai"} -add_crewai_flow_fastapi_endpoint(app, OpenBotFlow(), "/") +add_crewai_flow_fastapi_endpoint(app, OpenBotAgentFlow(), "/", conversational=True) diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index a46d33fac6..58c9ffb3aa 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -15,7 +15,7 @@ import uvicorn from fastapi import FastAPI, Request from fastapi.testclient import TestClient -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, StreamingResponse sys.path.insert(0, str(Path(__file__).resolve().parents[1])) @@ -77,81 +77,14 @@ def test_model_normalizes_blank_provider_and_model_before_defaults( assert main._model() == expected -def test_crewai_endpoint_preserves_leading_bot_role_for_provider(monkeypatch): - monkeypatch.setenv("MANAGED_AGENT_TOKEN", "test-token") - provider_messages = [] - provider_tools = [] - - async def record_completion(*, model, messages, tools, stream): - provider_messages.append(deepcopy(messages)) - provider_tools.append(deepcopy(tools)) - return FakeCompletion() - - monkeypatch.setattr(main, "acompletion", record_completion) - - client = TestClient(main.app) - response = client.post( - "/", - headers={"x-openbot-agent-token": "test-token"}, - json=run_input( - [ - { - "id": "system-1", - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "id": "user-1", - "role": "user", - "content": "What should I review first?", - }, - ] - ), - ) - - assert response.status_code == 200 - assert provider_messages == [ - [ - { - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "role": "user", - "content": "What should I review first?", - }, - ] - ] - assert provider_tools == [None] - snapshots = [ - event["messages"] - for event in agui_events(response.text) - if event.get("type") == "MESSAGES_SNAPSHOT" - ] - assert snapshots - assert snapshots[-1][:2] == [ - { - "id": "system-1", - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "id": "user-1", - "role": "user", - "content": "What should I review first?", - }, - ] - - -def test_provider_message_projection_keeps_supported_fields_without_mutating_state(): +def test_session_messages_are_projected_to_provider_fields_without_mutating_state(): + """What the Agent is given is what a strict provider accepts; the session keeps the rest.""" original_messages = [ { "id": "system-1", "role": "system", "content": "System instructions", - "name": "system_name", "metadata": {"transport": "ag-ui"}, - "encrypted_value": "system-secret", }, { "id": "user-1", @@ -166,7 +99,6 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta { "id": "assistant-1", "role": "assistant", - "content": None, "name": "assistant_name", "tool_calls": [ { @@ -189,14 +121,10 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta ] state_messages = deepcopy(original_messages) - projected = main._provider_messages(state_messages) + projected = [main._message_dict(message) for message in state_messages] assert projected == [ - { - "role": "system", - "content": "System instructions", - "name": "system_name", - }, + None, { "role": "user", "content": [ @@ -207,6 +135,7 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta }, { "role": "assistant", + "content": None, "name": "assistant_name", "tool_calls": [ { @@ -225,6 +154,26 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta assert state_messages == original_messages +def test_every_system_message_of_the_run_is_kept_for_the_agent(): + """ag-ui-crewai's conversational path drops system messages; the Bot's role is among them.""" + from ag_ui.core import SystemMessage, UserMessage + + inputs = main.crewai_endpoint.crewai_prepare_inputs( + state={}, + messages=[ + SystemMessage(id="standing-role:bot", role="system", content="You are Ada."), + SystemMessage(id="granted-tools:bot", role="system", content="You hold: notes."), + UserMessage(id="u1", role="user", content="Hello"), + ], + tools=[], + context=[], + forwarded_props={}, + ) + + assert inputs[main.INSTRUCTIONS_KEY] == ["You are Ada.", "You hold: notes."] + assert inputs[main.CALLER_TOOLS_KEY] == [] + + def isolated_environment(directory): directory.mkdir(parents=True, exist_ok=True) inherited = ( @@ -286,18 +235,55 @@ def stop_loopback_server(server, thread): assert not thread.is_alive(), "loopback server did not stop" +def as_stream(completion): + """A Chat Completions answer as the SSE stream a streamed request gets.""" + message = completion["choices"][0]["message"] + delta = {key: value for key, value in message.items() if value is not None} + for index, call in enumerate(delta.get("tool_calls") or []): + call["index"] = index + base = { + "id": completion["id"], + "object": "chat.completion.chunk", + "created": completion["created"], + "model": completion["model"], + } + chunks = [ + {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + { + **base, + "choices": [ + {"index": 0, "delta": {}, "finish_reason": completion["choices"][0]["finish_reason"]} + ], + }, + {**base, "choices": [], "usage": completion["usage"]}, + ] + + async def stream(): + for chunk in chunks: + yield f"data: {json.dumps(chunk)}\n\n" + yield "data: [DONE]\n\n" + + return StreamingResponse(stream(), media_type="text/event-stream") + + def loopback_openai_receiver(records, strict_messages=False): app = FastAPI() @app.post("/chat/completions") async def chat_completions(request: Request): body = await request.json() + completion = answer(body, request.headers) + if isinstance(completion, dict) and body.get("stream"): + return as_stream(completion) + return completion + + def answer(body, headers): records.append( { "model": body.get("model"), "messages": body.get("messages"), "tools": body.get("tools"), - "authorization": request.headers.get("authorization"), + "authorization": headers.get("authorization"), } ) if not body.get("model"): @@ -343,7 +329,7 @@ async def chat_completions(request: Request): }, status_code=400, ) - if body.get("tools") == [show_note_provider_tool()] and not any( + if provider_tool_shapes(body.get("tools")) == [show_note_shape()] and not any( message.get("role") == "tool" for message in body.get("messages") or [] ): return { @@ -457,7 +443,7 @@ def agui_events(response_text): return events -def run_litellm_loopback_proof(proof_case, output): +def run_loopback_proof(proof_case, output): sys.addaudithook(prohibit_external_connections) provider, model, expected_provider_model, expected_receiver_model = { "blank-provider": (" ", "gpt-4o", "openai/gpt-4o", "gpt-4o"), @@ -580,12 +566,23 @@ def run_litellm_loopback_proof(proof_case, output): assert not result["runError"], result assert len(records) == (2 if proof_case == "caller-tool" else 1), result assert all(record["model"] == expected_receiver_model for record in records), result - assert records[0]["messages"][0] == { + # CrewAI's own system prompt for the Agent, then the Bot's role as the server sent it. + assert records[0]["messages"][0]["role"] == "system", result + assert records[0]["messages"][1] == { "role": "system", "content": "You are Ada, a Bot-specific finance analyst.", }, result if proof_case == "caller-tool": - assert records[0]["tools"] == [show_note_provider_tool()], result + assert provider_tool_shapes(records[0]["tools"]) == [show_note_shape()], result + # Handed back, not run: no result on the wire and none in the thread, and the one call the + # snapshot asks for is the model's own. + assert "TOOL_CALL_RESULT" not in result["eventTypes"], result + assert "TOOL_CALL_START" not in result["eventTypes"], result + first_snapshot = result["messagesSnapshots"][-1] + assert not [m for m in first_snapshot if m["role"] == "tool"], result + assert [call["id"] for m in first_snapshot for call in m.get("toolCalls") or []] == [ + "call_show_note_1" + ], result assert result["decodedToolCall"] == { "id": "call_show_note_1", "type": "function", @@ -596,8 +593,8 @@ def run_litellm_loopback_proof(proof_case, output): }, result assert result["secondStatusCode"] == 200, result assert "RUN_FINISHED" in result["secondEventTypes"], result - assert records[1]["tools"] == [show_note_provider_tool()], result - assert records[1]["messages"][-2:] == [ + assert provider_tool_shapes(records[1]["tools"]) == [show_note_shape()], result + assert without_empty_content(records[1]["messages"][-2:]) == [ { "role": "assistant", "tool_calls": [ @@ -620,28 +617,72 @@ def run_litellm_loopback_proof(proof_case, output): assert result["messagesSnapshots"][-1][-1]["toolCalls"][0]["id"] == "call_show_note_1" elif proof_case == "strict-projection": assert_provider_messages_are_projected(records[0]["messages"]) - assert records[0]["messages"][1] == { + # The picture reaches the model, just before the question CrewAI makes the request. + assert records[0]["messages"][2] == { "role": "user", "content": [ - {"type": "text", "text": "What should I review first?"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, ], "name": "analyst", }, result + assert records[0]["messages"][3]["role"] == "user", result + assert "What should I review first?" in records[0]["messages"][3]["content"], result + assert without_empty_content(records[0]["messages"][4:]) == [ + { + "role": "assistant", + "tool_calls": [ + { + "id": "call-1", + "type": "function", + "function": {"name": "lookup", "arguments": "{\"symbol\":\"ACME\"}"}, + } + ], + }, + {"role": "tool", "content": "Synthetic result", "tool_call_id": "call-1"}, + ], result + # Every message of the thread keeps the id it arrived under, so the snapshot replaces the + # client's copies instead of adding the thread again under new ones. It carries no system + # message, which leaves the client's as they are. snapshot = result["messagesSnapshots"][-1] - assert [message["id"] for message in snapshot[:4]] == [ - "system-1", + assert [message["id"] for message in snapshot[:3]] == [ "user-1", "assistant-1", "tool-1", ], result - assert snapshot[2]["toolCalls"][0]["id"] == "call-1", result - assert snapshot[3]["toolCallId"] == "call-1", result + assert not [message for message in snapshot if message["role"] == "system"], result + assert snapshot[1]["toolCalls"][0]["id"] == "call-1", result + assert snapshot[2]["toolCallId"] == "call-1", result else: - assert records[0]["messages"][1] == { - "role": "user", - "content": "What should I review first?", - }, result + assert records[0]["messages"][2]["role"] == "user", result + assert "What should I review first?" in records[0]["messages"][2]["content"], result + + +def without_empty_content(messages): + """CrewAI sends `content: null` on a message that only calls tools; the old harness left it out.""" + return [ + {key: value for key, value in message.items() if not (key == "content" and value is None)} + for message in messages + ] + + +def show_note_shape(): + return { + "name": "show_note", + "properties": {"title"}, + "required": ["title"], + } + + +def provider_tool_shapes(tools): + """The tools the model was offered, by what matters: CrewAI writes its own schema around them.""" + return [ + { + "name": tool["function"]["name"], + "properties": set(tool["function"]["parameters"]["properties"]), + "required": tool["function"]["parameters"].get("required"), + } + for tool in tools or [] + ] def basic_messages(): @@ -733,7 +774,7 @@ def assert_provider_messages_are_projected(messages): "proof_case", ["blank-provider", "blank-model", "strict-projection", "namespaced-model", "gateway-model"], ) -def test_crewai_endpoint_uses_normalized_model_with_real_litellm_loopback( +def test_crewai_endpoint_uses_normalized_model_with_real_provider_loopback( tmp_path, proof_case ): output = tmp_path / f"{proof_case}.json" @@ -791,4 +832,4 @@ def test_crewai_endpoint_forwards_caller_tools_and_accepts_tool_result_continuat ) parser.add_argument("--output", type=Path, required=True) arguments = parser.parse_args() - run_litellm_loopback_proof(arguments.proof_case, arguments.output) + run_loopback_proof(arguments.proof_case, arguments.output) diff --git a/docs/agent-frameworks.md b/docs/agent-frameworks.md index 1da569e9a2..af5ad7288f 100644 --- a/docs/agent-frameworks.md +++ b/docs/agent-frameworks.md @@ -165,6 +165,20 @@ app.include_router(router) Your flow then reads the role and the guidance in `self.state.messages`. Choose **CrewAI** in New Bot. +### A conversational CrewAI Agent + +An `Agent(conversational=True)` served with `add_crewai_flow_fastapi_endpoint(..., conversational=True)` +needs more than the route above. That path drops every system message of a run, not only the first. +CrewAI also runs an Agent's tools itself, while the tools OpenBot gives a Bot are run by the server. +The Bot asks for one and the run ends. Finally, the adapter gives each earlier message of the thread a +new id in its snapshots, so the app shows the conversation twice. + +OpenBot's own CrewAI Bot is built this way, and +[`agent-crewai/src/main.py`](../agent-crewai/src/main.py) handles all three. It keeps the run's system +messages for the Agent and turns OpenBot's tools into tools that hand the call back. It also keeps +each message's id. Start from that file and give the Agent your own role, goal and tools. Tools you +add run in your process as usual. + ## Claude Agent SDK `ag-ui-claude-sdk` sends Claude only the last message of a run, so the system messages never reach From aea91a645dc1db8db21b328f4a5ac39d11a036e8 Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 17:55:38 -0800 Subject: [PATCH 002/224] CrewAI Bot: serialize in-place session messages as session messages A live run appends the current user message to the session as a plain dict, and CrewAI appends its base ConversationMessage. Pydantic never sees in-place appends, and CrewAI serializes the state on every step, so every run logged "serialized value may not be as expected". The state's serializer now coerces those entries, leaving the list itself untouched. Co-Authored-By: Claude Opus 5.5 --- agent-crewai/src/main.py | 36 ++++++++++++++++++++++++++++++++- agent-crewai/tests/test_main.py | 32 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 67ead52f2b..39df3e222b 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -57,7 +57,14 @@ from crewai.utilities.pydantic_schema_utils import create_model_from_schema from fastapi import FastAPI, Request from fastapi.responses import JSONResponse -from pydantic import BaseModel, Field, PrivateAttr, field_validator +from pydantic import ( + BaseModel, + Field, + PrivateAttr, + SerializerFunctionWrapHandler, + field_serializer, + field_validator, +) # The one header OpenBot's server sends when it calls a managed Bot. Same name the TypeScript Bots # check, because a Bot is a Bot whatever it is written in. @@ -371,6 +378,33 @@ def content_may_be_empty(cls, value: Any) -> Any: ] return value + @field_serializer("messages", mode="wrap") + def messages_as_session_messages( + self, value: Any, handler: SerializerFunctionWrapHandler + ) -> Any: + """Messages appended to the list after validation are serialized as session messages too. + + The session's list is appended to in place, which pydantic never sees: the current user + message arrives as a plain dict, and CrewAI's own appends are its base `ConversationMessage`. + CrewAI serializes the state on every step, so each of those logged a pydantic "serialized value + may not be as expected" warning on every run. Coerced here, they serialize as the messages + they are, and the list itself is left as it is. + """ + if isinstance(value, list): + value = [_session_message(message) for message in value] + return handler(value) + + +def _session_message(message: Any) -> Any: + """One entry of the session's list, as the message the state declares.""" + if isinstance(message, OpenBotConversationMessage): + return message + if isinstance(message, BaseModel): + message = message.model_dump() + if isinstance(message, dict): + return OpenBotConversationMessage.model_validate({"content": None, **message}) + return message + def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: """The newest user message's pictures and files, kept as a message of their own. diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index 58c9ffb3aa..00471fc5ad 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -174,6 +174,38 @@ def test_every_system_message_of_the_run_is_kept_for_the_agent(): assert inputs[main.CALLER_TOOLS_KEY] == [] +def test_messages_appended_after_validation_serialize_without_a_warning(): + """A live run appends the user message as a dict and CrewAI appends its base message class. + + CrewAI serializes the state on every step, and each of those used to log pydantic's + "serialized value may not be as expected" on every run. + """ + import warnings + + from crewai.flow.conversational import ConversationMessage + + state = main.OpenBotConversationState() + # Appended the way a run appends them: in place, past validation. + session: list = state.messages + session.append({"role": "user", "content": "Hello", "metadata": {}, "id": "u1"}) + session.append(ConversationMessage(role="assistant", content="Hi")) + session.append({"role": "assistant", "tool_calls": [], "id": "a2"}) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + dumped = state.model_dump(mode="json") + copied = state.model_copy(deep=True).model_dump() + + assert [(m["role"], m["content"], m["id"]) for m in dumped["messages"]] == [ + ("user", "Hello", "u1"), + ("assistant", "Hi", None), + ("assistant", None, "a2"), + ] + assert copied["messages"] == dumped["messages"] + # Serializing does not rewrite the session's own list. + assert isinstance(state.messages[0], dict) + + def isolated_environment(directory): directory.mkdir(parents=True, exist_ok=True) inherited = ( From 96526136995f3cb850e0a6177a064a84d1bcb91d Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 19:28:58 -0800 Subject: [PATCH 003/224] CrewAI Bot: Gemini gets tool names, its own image parts and signed tool calls CrewAI's Gemini client failed every run that followed an OpenBot tool, and dropped images: - A tool result now carries the name of the tool it answers, taken from the matching tool call; Gemini refuses an empty function_response name. - Image parts become Gemini's inlineData / fileData parts, the only image parts CrewAI's Gemini client reads. - A replayed tool call carries Google's documented placeholder thought signature, since AG-UI has nowhere to keep the real one between runs. All three apply to Google only: a strict OpenAI-compatible server refuses a name on a tool message. Co-Authored-By: Claude Opus 5.5 --- agent-crewai/src/main.py | 100 +++++++++++++++++++++++++++++++- agent-crewai/tests/test_main.py | 64 ++++++++++++++++++++ 2 files changed, 163 insertions(+), 1 deletion(-) diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 39df3e222b..5694b263c9 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -30,6 +30,7 @@ import hmac import json +import mimetypes import os import sys import threading @@ -435,6 +436,101 @@ def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, An return conversation +def _with_tool_names(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Each tool result names the tool it answers, read off the call it answers. + + AG-UI's tool message carries only the call's id. Gemini's function response needs the + function's name, and CrewAI's Gemini client reads it from the message, so without it every run + after the server ran a tool was refused ("function_response.name: Name cannot be empty"). + Gemini's only: an OpenAI-compatible server that accepts no field beyond the spec's refuses a + tool message that carries a name, and the others go by the id. + """ + names: dict[str, str] = {} + named: list[dict[str, Any]] = [] + for message in conversation: + for call in message.get("tool_calls") or []: + function = call.get("function") or {} + if call.get("id") and function.get("name"): + names[call["id"]] = function["name"] + if message.get("role") == "tool" and not message.get("name"): + name = names.get(message.get("tool_call_id") or "") + if name: + message = {**message, "name": name} + named.append(message) + return named + + +def _gemini_part(part: Any) -> Any: + """An `image_url` part as the inline data CrewAI's Gemini client reads. + + That client turns only `text`, `inlineData` and `fileData` parts into Gemini parts and drops + the rest without a word, so a picture the person sent never reached the model ("No image + provided"). A data URL carries its own type; an address is handed over as a file by URI with + the type its name implies, which Gemini needs. + """ + if not (isinstance(part, dict) and part.get("type") == "image_url"): + return part + url = str((part.get("image_url") or {}).get("url") or "") + if url.startswith("data:") and ";base64," in url: + header, data = url[len("data:") :].split(";base64,", 1) + return {"inlineData": {"mimeType": header or "application/octet-stream", "data": data}} + if url.startswith(("https://", "http://")): + mime_type, _ = mimetypes.guess_type(url.split("?", 1)[0]) + return {"fileData": {"fileUri": url, "mimeType": mime_type or "image/jpeg"}} + return part + + +# Gemini 3 refuses a function call in the history that does not carry the thought signature it was +# made with ("Function call is missing a thought_signature"). OpenBot runs each tool between two +# runs, and AG-UI's tool call has no field for a signature, so a call always comes back without +# its own. Keeping the real one would mean holding it between runs, on whichever replica answered +# the first. Google documents this value for a history whose signatures are not available. +GEMINI_UNSIGNED_CALL = b"skip_thought_signature_validator" + + +def _gemini_tool_call_parts(message: dict[str, Any]) -> list[Any]: + """The assistant's tool calls as Gemini parts, each carrying the unsigned-call signature. + + CrewAI's Gemini client sends `raw_tool_call_parts` as they are, in place of the parts it would + build from `tool_calls` without a signature. + """ + from google.genai import types + + parts = [] + for call in message.get("tool_calls") or []: + function = call.get("function") or {} + arguments = function.get("arguments") or {} + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) if arguments else {} + except ValueError: + arguments = {} + parts.append( + types.Part( + function_call=types.FunctionCall( + name=str(function.get("name") or ""), + args=arguments if isinstance(arguments, dict) else {}, + ), + thought_signature=GEMINI_UNSIGNED_CALL, + ) + ) + return parts + + +def _for_provider(conversation: list[dict[str, Any]], provider: str) -> list[dict[str, Any]]: + """The conversation in the shape this provider's CrewAI client reads.""" + if provider != "google": + return conversation + shaped = [] + for message in _with_tool_names(conversation): + if isinstance(message.get("content"), list): + message = {**message, "content": [_gemini_part(part) for part in message["content"]]} + if message.get("role") == "assistant" and message.get("tool_calls"): + message = {**message, "raw_tool_call_parts": _gemini_tool_call_parts(message)} + shaped.append(message) + return shaped + + def _agent(tools: list[CallerTool]) -> Agent: """The Bot, as a CrewAI Agent, for one turn. @@ -483,7 +579,9 @@ async def converse_turn(self): ] if not conversation: raise ValueError("A turn needs at least one message") - conversation = _with_request_media(conversation) + conversation = _for_provider( + _with_request_media(conversation), bot_settings("agent-crewai").provider + ) hand_back = HandBack() tools = _caller_tools(self.state.openbot_caller_tools, hand_back) agent = _agent(tools) diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index 00471fc5ad..981443b1e0 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -174,6 +174,70 @@ def test_every_system_message_of_the_run_is_kept_for_the_agent(): assert inputs[main.CALLER_TOOLS_KEY] == [] +def test_tool_results_name_the_tool_they_answer(): + """Gemini refuses a function response without the function's name; AG-UI sends only the id.""" + conversation = [ + {"role": "user", "content": "Weather in Lisbon and Rome?"}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}, + {"id": "call-2", "type": "function", "function": {"name": "show_note", "arguments": "{}"}}, + ], + }, + {"role": "tool", "tool_call_id": "call-2", "content": "shown"}, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny", "name": "kept"}, + {"role": "tool", "tool_call_id": "call-unknown", "content": "?"}, + ] + original = deepcopy(conversation) + + named = main._with_tool_names(conversation) + + assert [m.get("name") for m in named[2:]] == ["show_note", "kept", None] + assert conversation == original + + +def test_gemini_gets_its_own_image_parts_and_unsigned_tool_calls(): + """CrewAI's Gemini client drops `image_url` parts, and Gemini 3 refuses an unsigned call.""" + conversation = [ + { + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, + {"type": "image_url", "image_url": {"url": "https://example.com/files/cat.jpg?x=1"}}, + {"type": "text", "text": "What is this?"}, + ], + }, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Lisbon"}'}}, + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, + ] + + # Only Gemini's: a strict OpenAI-compatible server refuses a named tool message. + assert main._for_provider(conversation, "openai") is conversation + assert main._for_provider(conversation, "anthropic") is conversation + shaped = main._for_provider(conversation, "google") + + assert shaped[0]["content"] == [ + {"inlineData": {"mimeType": "image/png", "data": "AAAA"}}, + {"fileData": {"fileUri": "https://example.com/files/cat.jpg?x=1", "mimeType": "image/jpeg"}}, + {"type": "text", "text": "What is this?"}, + ] + [part] = shaped[1]["raw_tool_call_parts"] + assert part.function_call.name == "get_weather" + assert part.function_call.args == {"city": "Lisbon"} + assert part.thought_signature == main.GEMINI_UNSIGNED_CALL + assert shaped[2] == {**conversation[2], "name": "get_weather"} + assert "raw_tool_call_parts" not in conversation[1] + assert "name" not in conversation[2] + + def test_messages_appended_after_validation_serialize_without_a_warning(): """A live run appends the user message as a dict and CrewAI appends its base message class. From 1a8db266d3e5e06954bac844236a481c37a457d6 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 14:39:32 -0800 Subject: [PATCH 004/224] Show a command the person stopped as stopped, not running (#2558) Pressing Stop while a Bot ran a command left its line saying "Running a command" after the Bot had stopped. The server runs the command in the Bot's run, and its answer reaches the page in that run's stream, which the Stop closes. The line read "running" from the call having no answer, whether or not its turn was still going. Opened again, the runtime's own answer for the stopped step ({ status: "stopped" }) read as a command that didn't run. A command with no answer is now running only while its turn is. Once the turn is over, or with the runtime's stopped answer, its line reads "Run a command, interrupted" and its card "Not completed", the words a Claude Code command left by a stopped turn already uses. In a folded run of steps its row reads "Run a command" with "Not completed". This is the page's reading of the conversation, so built-in and connected AG-UI Bots get the same. Tests: the real conversation in Chromium and WebKit, light and dark, wide and on a phone: a command under way, Stop pressed, the line no longer running, and the same after the conversation is opened again with the runtime's answer and with none (fails before). A folded run's row reads not completed rather than running or didn't work (fails before). --- .github/workflows/ci.yml | 4 +- app/src/components/channels/tool-activity.tsx | 36 +- .../components/computer/terminal-block.tsx | 88 ++- app/src/lib/computers/activity.ts | 8 +- app/src/lib/copilot/computer-tools.tsx | 32 +- app/tests/run-ended-unheard.fixture.tsx | 4 +- app/tests/stopped-command-layout.test.tsx | 499 ++++++++++++++++++ app/tests/stopped-command-step.test.tsx | 108 ++++ 8 files changed, 739 insertions(+), 40 deletions(-) create mode 100644 app/tests/stopped-command-layout.test.tsx create mode 100644 app/tests/stopped-command-step.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9519dac495..e5e25abcb6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -445,6 +445,8 @@ jobs: # its own renderer under this job's load. # And Sign in with Apple's button white with its logo and title black, in both themes and every # state, lined up with the sign-in buttons beside it, and People naming Apple. + # And a command the person stopped reading as stopped, not running, at once and when the + # conversation is opened again. # And that what is already drawn does not move: Home's heading and box when the page finishes # loading, and the app's frame drawn while the sign-in checks run when the page behind it # arrives. In the image, as above: WebKit's @@ -491,7 +493,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx + bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx app/tests/stopped-command-layout.test.tsx # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. - run: | diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index a511984aaa..80b751fcfa 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -47,6 +47,7 @@ import { STILL_STARTING_DETAIL, TerminalBlock, } from "@/components/computer/terminal-block"; +import { TurnInFlightContext } from "@/components/gallery/streaming"; import { settingsToolCardFor } from "@/components/settings-tools/settings-tool-card"; import { useOverflows } from "@/hooks/use-overflows"; import { readOutcome } from "@/lib/computers/activity"; @@ -374,6 +375,11 @@ export type StepDetails = { * running: it is named as it was while under way, and counted apart from what the run did. */ interrupted?: boolean; + /** + * Its turn was stopped before it answered, which the runtime may have answered for it since: not + * completed, as a step with no answer reads once its turn is over. Only a command says so. + */ + stopped?: boolean; reason?: string; /** Pages a browser step opened, or a fetch read; zero for anything else. */ pages: number; @@ -470,14 +476,22 @@ export function stepDetails(step: ToolItem): StepDetails { return detailsOf(step, new Map()); } -/** `stepDetails`, naming a folder step's folder from the conversation's folder names. */ +/** + * `stepDetails`, naming a folder step's folder from the conversation's folder names. `live`: the + * steps' turn is still going. Once it is over, a command with no answer was stopped under way. + */ export function stepDetailsIn( folders: FolderNames, + live = true, ): (step: ToolItem) => StepDetails { - return (step) => detailsOf(step, folders); + return (step) => detailsOf(step, folders, live); } -function detailsOf(step: ToolItem, folders: FolderNames): StepDetails { +function detailsOf( + step: ToolItem, + folders: FolderNames, + live = true, +): StepDetails { if (cutOffStep(step.result)) { // Read as the step it was while under way, then marked: what the Bot was told is not shown. const { result: _told, ...underWay } = step; @@ -518,7 +532,8 @@ function detailsOf(step: ToolItem, folders: FolderNames): StepDetails { const name = step.toolCall.function.name; if (name === SUBAGENT_TOOL) return subtaskDetails(step, args); - if (COMPUTER_WORK.has(name)) return computerStepDetails(step, name, args); + if (COMPUTER_WORK.has(name)) + return computerStepDetails(step, name, args, live); const look = codingLook(name, step.toolCall.function.arguments); if (look !== null) { // Running whenever it has no result: whether the turn still is, the step's status says. @@ -690,18 +705,21 @@ function computerStepDetails( step: ToolItem, name: string, args: Record, + live: boolean, ): StepDetails { // No answer yet, or only the placeholder of a step held for the person. const outcome = readOutcome(step.result); const pending = outcome === null; if (name === "computer_run_command") { - const terminal = commandCall(args.command, step.result, pending); + const terminal = commandCall(args.command, step.result, live); return { id: step.id, kind: "command", ...commandStepWords(terminal.status), ...(terminal.command ? { detail: terminal.command } : {}), pending, + // "Not completed" beside it, as a step with no answer reads once its turn is over. + ...(terminal.status.state === "stopped" ? { stopped: true } : {}), pages: 0, inputs: [], terminal, @@ -973,10 +991,10 @@ export function StepStatus({ step: StepDetails; active: boolean; }) { - if (step.pending) + if (step.pending || step.stopped) return ( - {active ? "In progress" : "Not completed"} + {active && step.pending ? "In progress" : "Not completed"} ); if (step.interrupted) @@ -1243,7 +1261,9 @@ export function ToolActivity({ active: boolean; }) { const folders = useContext(FolderNamesContext); - const steps = group.steps.map(stepDetailsIn(folders)); + // A command with no answer runs while its turn does, whichever row it is in. + const inFlight = useContext(TurnInFlightContext); + const steps = group.steps.map(stepDetailsIn(folders, active || inFlight)); // What the line opens to: a run of rereads is one row. See `foldRereads`. const rows = foldRereads(steps); const running = active && steps.some((step) => step.pending); diff --git a/app/src/components/computer/terminal-block.tsx b/app/src/components/computer/terminal-block.tsx index 6e0bfedc05..1400a46a2d 100644 --- a/app/src/components/computer/terminal-block.tsx +++ b/app/src/components/computer/terminal-block.tsx @@ -33,6 +33,8 @@ const SHOWN_LINES = 4; export type TerminalBlockStatus = | { state: "running" } | { state: "starting" } + /** Under way when its turn was stopped: nobody knows how far it got. See `commandCall`. */ + | { state: "stopped" } | { state: "exited"; exitCode: number; timedOut?: boolean } | { state: "blocked" | "declined" | "by-you" | "failed"; reason?: string }; @@ -48,23 +50,26 @@ function StatusBadge({ status }: { status: TerminalBlockStatus }) { ? ["neutral", "Running", null] : status.state === "starting" ? ["caution", "Computer starting", null] - : status.state === "exited" - ? status.timedOut - ? ["caution", "Stopped: too long", null] - : status.exitCode === 0 - ? [ - "positive", - "Exit 0", - , - ] - : ["negative", `Exit ${status.exitCode}`, null] - : status.state === "blocked" - ? ["negative", "Blocked", null] - : status.state === "declined" - ? ["neutral", "Declined", null] - : status.state === "by-you" - ? ["neutral", "Done by you", null] - : ["negative", "Didn't run", null]; + : // What a Claude Code command left by a stopped turn says (`OutcomeStatus`). + status.state === "stopped" + ? ["neutral", "Not completed", null] + : status.state === "exited" + ? status.timedOut + ? ["caution", "Stopped: too long", null] + : status.exitCode === 0 + ? [ + "positive", + "Exit 0", + , + ] + : ["negative", `Exit ${status.exitCode}`, null] + : status.state === "blocked" + ? ["negative", "Blocked", null] + : status.state === "declined" + ? ["neutral", "Declined", null] + : status.state === "by-you" + ? ["neutral", "Done by you", null] + : ["negative", "Didn't run", null]; return ( ; + const answered = readOutcome(result); + const outcome = (answered ?? {}) as Partial; const refused = outcome.refused === true; const starting = outcome.ok === false && outcome.starting === true; + const stopped = + answered === null + ? !live + : outcome.ok === false && + (outcome.stopped === true || outcome.runStopped === true); return { command: typeof command === "string" ? command : "", - output: refused - ? outcomeForPerson(String(outcome.reason ?? "")) - : starting - ? STILL_STARTING_DETAIL - : outputOf(outcome as ToolOutcome), + output: stopped + ? "" + : refused + ? outcomeForPerson(String(outcome.reason ?? "")) + : starting + ? STILL_STARTING_DETAIL + : outputOf(outcome as ToolOutcome), status: commandStatus({ - running, + running: answered === null && live, + stopped, starting, refused, declined: outcome.declined === true, @@ -373,6 +406,9 @@ export function commandStepWords(status: TerminalBlockStatus): { failed: false, refused: false, }; + // The row puts "Not completed" beside it (`StepStatus`). + case "stopped": + return { label: "Run a command", failed: false, refused: false }; case "exited": return { label: "Ran a command", @@ -396,6 +432,7 @@ export function commandStepWords(status: TerminalBlockStatus): { /** What a command's result says about how it ended, for the block's badge. */ export function commandStatus(input: { running: boolean; + stopped?: boolean; starting?: boolean; refused?: boolean; declined?: boolean; @@ -405,6 +442,7 @@ export function commandStatus(input: { failed?: boolean; }): TerminalBlockStatus { if (input.running) return { state: "running" }; + if (input.stopped) return { state: "stopped" }; if (input.starting) return { state: "starting" }; if (input.declined) return { state: "declined" }; if (input.refused) return { state: "blocked" }; diff --git a/app/src/lib/computers/activity.ts b/app/src/lib/computers/activity.ts index b69545f73e..3e76d681b6 100644 --- a/app/src/lib/computers/activity.ts +++ b/app/src/lib/computers/activity.ts @@ -628,7 +628,13 @@ export function readOutcome(content: unknown): ToolOutcome | null { (outcome.status === "stopped" || outcome.status === "error") && typeof outcome.message === "string" ) - return { ...outcome, ok: false, reason: outcome.message }; + return { + ...outcome, + ok: false, + reason: outcome.message, + // The person's Stop: a command reads as stopped under way (`commandCall`). + ...(outcome.status === "stopped" ? { runStopped: true } : {}), + }; /* * A STEP CUT OFF INSIDE THE SERVER'S OWN RUN, as the server answers it there: `{ ok: false, * error: "Outcome unknown: ..." }`. Read as the sentence on its own is (below): not run, and diff --git a/app/src/lib/copilot/computer-tools.tsx b/app/src/lib/copilot/computer-tools.tsx index 28e6c9c0d6..0bc3976903 100644 --- a/app/src/lib/copilot/computer-tools.tsx +++ b/app/src/lib/copilot/computer-tools.tsx @@ -5,6 +5,7 @@ import { SEND_FILE_TOOL, SEND_FILE_TOOL_DESCRIPTION, } from "@openbot/shared/send-file"; +import { useContext } from "react"; import { z } from "zod"; import { SentFileCard } from "@/components/channels/sent-file-card"; import { ToolLine } from "@/components/channels/tool-line"; @@ -15,6 +16,7 @@ import { STILL_STARTING_DETAIL, TerminalStep, } from "@/components/computer/terminal-block"; +import { TurnInFlightContext } from "@/components/gallery/streaming"; import { reportBotDecline } from "@/lib/api/generated/bots/bots"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { noteBrowsed, readOutcome } from "@/lib/computers/activity"; @@ -75,6 +77,29 @@ async function waitForSecret( return "gave up"; } +/** + * A command's line, running only while its turn is. The SDK's status says `inProgress` for any call + * with no answer, so a command whose turn the person stopped read "Running a command" for good; with + * its turn over and no answer, it was stopped under way (`commandCall`). + */ +function CommandLine({ + computerId, + command, + result, +}: { + computerId: string | undefined; + command: unknown; + result: string | undefined; +}) { + const live = useContext(TurnInFlightContext); + return ( + + ); +} + /** What a computer tool's render can read back out of its own result. */ type ComputerOutcome = { ok?: boolean; @@ -899,10 +924,11 @@ export function ComputerTools() { * holding somebody's logins, so what it printed is always reachable here rather than taken on * the model's word. Beside other steps it is one row of their folded line (`ToolActivity`). */ - render: ({ args, result, status }) => ( - ( + ), }); diff --git a/app/tests/run-ended-unheard.fixture.tsx b/app/tests/run-ended-unheard.fixture.tsx index 7182c27cbb..fb0644ad8d 100644 --- a/app/tests/run-ended-unheard.fixture.tsx +++ b/app/tests/run-ended-unheard.fixture.tsx @@ -26,8 +26,8 @@ import { setCurrentOrganization } from "@/lib/organizations/current"; import { queryClient } from "@/query-client"; /** - * A conversation with a Bot, as a page of its own for run-ended-unheard-layout.test.tsx to bundle and - * load in a browser: the real conversation in the app's real frame (its sidebar and inset panel, as + * A conversation with a Bot, as a page of its own for run-ended-unheard-layout.test.tsx (and + * stopped-command-layout.test.tsx) to bundle and load in a browser: the real conversation in the app's real frame (its sidebar and inset panel, as * `routes/_authed/_app.tsx` draws them), with the runtime client the app uses. What the server * answers comes from the test's server. * diff --git a/app/tests/stopped-command-layout.test.tsx b/app/tests/stopped-command-layout.test.tsx new file mode 100644 index 0000000000..fc2c2b6476 --- /dev/null +++ b/app/tests/stopped-command-layout.test.tsx @@ -0,0 +1,499 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Server } from "bun"; +import type { Browser, BrowserType, Locator, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { personBody } from "./accounts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; + +/** + * A command the person stopped reads as stopped, not running, then and after the conversation is + * opened again, in a real browser. + * + * Found on 2026-11-30: Stop pressed while a Bot ran a command, and 30 seconds later, the Stop button + * long gone, the command's line still said "Running a command". The server runs a Bot's command in + * the Bot's run, and its answer reaches the page in that run's stream, which the Stop closes; the + * line read "running" from the call having no answer. Opened again, the conversation read it from + * whatever the thread kept: nothing, or the runtime's own answer for a step its run was stopped + * under (`{ status: "stopped", ... }`). + * + * The real conversation in the app's frame (the fixture `run-ended-unheard-layout.test.tsx` draws + * too), with the app's stylesheet, against a real HTTP server on this machine at the API's and the + * runtime's addresses. The run streams the Bot's words and its command, then nothing, as a run does + * while the server runs the command. The person sends with a real keyboard and presses Stop. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/stopped-command-layout.test.tsx + * + * Chromium by default. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With OPENBOT_APP_SHOTS= + * each moment is saved as stopped-command----.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "general-assistant"; +const CONVERSATION = "launch-conversation"; +const THREAD = "launch-thread"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; + +const ASKED = "Build the report and tell me when it's done."; +const ABOUT_TO = "I'll build the report now."; +const COMMAND = "pdflatex -interaction=nonstopmode report.tex"; +const CALL = "build"; +/** The runtime's answer for a step its run was stopped under, as the thread keeps it. */ +const RUNTIME_STOPPED = JSON.stringify({ + status: "stopped", + reason: "stop_requested", + message: "Run stopped by user", +}); + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "General Assistant", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, +}; + +/** What the thread holds, and how many commands the page sent to the gate itself. */ +let stored: unknown[] = []; +let gated = 0; + +const json = (body: unknown, status = 200) => + Response.json(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); +const frames = (events: unknown[]) => + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""); + +/** The thread once the Bot has asked for its command, with the runtime's answer for it or none. */ +function thread(person: unknown[], answer?: string): unknown[] { + return [ + ...person, + { + id: "about", + role: "assistant", + content: ABOUT_TO, + toolCalls: [ + { + id: CALL, + type: "function", + function: { + name: "computer_run_command", + arguments: JSON.stringify({ command: COMMAND }), + }, + }, + ], + }, + ...(answer === undefined + ? [] + : [{ id: "stopped", role: "tool", toolCallId: CALL, content: answer }]), + ]; +} + +/** Ends the run going, as the runtime does once it is asked to stop it. */ +let stopRun: (() => void) | undefined; + +/** + * The run: the Bot says what it will do and asks for its command, which the server is running. + * + * STOPPED, it ends with nothing more for this page: OpenBot's runtime acknowledges the Stop and the + * page lets the run go at once (`abortRun` in `@copilotkit/core`), so the runtime's own closing of + * the open step (`finalizeRunEvents` in `@copilotkit/shared`) reaches the thread, not the page. + */ +function run(input: { + threadId: string; + runId: string; + messages: unknown[]; + protocolVersion?: string; +}): Response { + stored = thread( + input.messages.filter( + (message) => (message as { role?: string }).role === "user", + ), + ); + const heard = [ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "TEXT_MESSAGE_START", messageId: "about", role: "assistant" }, + { type: "TEXT_MESSAGE_CONTENT", messageId: "about", delta: ABOUT_TO }, + { type: "TEXT_MESSAGE_END", messageId: "about" }, + { + type: "TOOL_CALL_START", + toolCallId: CALL, + toolCallName: "computer_run_command", + parentMessageId: "about", + }, + { + type: "TOOL_CALL_ARGS", + toolCallId: CALL, + delta: JSON.stringify({ command: COMMAND }), + }, + { type: "TOOL_CALL_END", toolCallId: CALL }, + ]; + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(frames(heard))); + stopRun = () => { + stopRun = undefined; + controller.enqueue( + new TextEncoder().encode( + frames([ + { + type: "RUN_FINISHED", + threadId: input.threadId, + runId: input.runId, + ...(input.protocolVersion !== undefined + ? { outcome: { type: "cancelled" } } + : {}), + }, + ]), + ), + ); + controller.close(); + }; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); +} + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "sse", + telemetryDisabled: true, + }); + // No run is going when the conversation is opened: nothing to replay. + if (path.endsWith("/connect")) + return new Response("", { + headers: { "content-type": "text/event-stream" }, + }); + if (path.endsWith("/run")) return run(await request.json()); + if (/\/agent\/[^/]+\/stop\//.test(path)) { + stopRun?.(); + return json({ stopped: true }); + } + // The page never runs the command itself: the server is running it in the Bot's run. + if (path === `${ORGANIZATION}/people/me/computer-steps`) { + gated += 1; + return json({ detail: "Not here." }, 500); + } + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "sam", + name: "Sam Rivera", + email: "sam.rivera@northwind.example", + role: "member", + }), + openbotVersion: "v1.2.3", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + joinToken: "jt", + expiresAt: "2026-11-30T18:20:30.000Z", + threadId: THREAD, + runId: null, + realtime: { clientUrl: "ws://127.0.0.1/client", topic: "thread" }, + }, + 201, + ); + if (/\/threads\/[^/]+\/messages$/.test(path)) + return json({ messages: stored }); + return undefined; +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "run-ended-unheard.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: Server | undefined; +let origin = ""; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + // A run's stream stays open while the server runs the command, as the runtime's does. + idleTimeout: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + const theme = new URL(request.url).searchParams.get("theme") ?? "light"; + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); + }, + }); + origin = `http://127.0.0.1:${server.port}`; + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + await server?.stop(true); +}); + +/** Styled for everything now on the page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +async function shoot(page: Page, name: string) { + await style(page); + await page.evaluate(() => document.fonts.ready); + await still(page); + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ path: join(shots, `${name}.png`) }); +} + +/** The command's line in the conversation, whatever it says of it. */ +function commandLine(page: Page): Locator { + return page + .locator("details") + .filter({ + has: page.locator(":scope > summary", { hasText: /a command/ }), + }) + .last(); +} + +/** What the command's line says, and whether it still shimmers as running. */ +async function readLine(page: Page) { + const line = commandLine(page); + await line.waitFor({ timeout: 30_000 }); + const summary = line.locator(":scope > summary"); + return { + says: ((await summary.textContent()) ?? "").replace(/\s+/g, " ").trim(), + shimmers: await summary.locator(".tool-line-running").count(), + }; +} + +/** The line reads as a command stopped under way, and opens to the block saying so. */ +async function expectStopped(page: Page) { + const line = await readLine(page); + expect(line.says).toContain("Run a command, interrupted"); + // Named by what ran, never by the runtime's words for the Stop. + expect(line.says).toContain(COMMAND); + expect(line.says).not.toContain("Running"); + expect(line.shimmers).toBe(0); + const block = commandLine(page); + await block.locator(":scope > summary").click(); + const card = block.locator("section[aria-label]"); + await card.waitFor(); + const text = ((await card.textContent()) ?? "").replace(/\s+/g, " "); + expect(text).toContain(COMMAND); + expect(text).toContain("Not completed"); + expect(text).not.toContain("Running"); + expect(await card.locator(".tool-line-running").count()).toBe(0); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); +} + +describe.skipIf(!asked)("a command the person stopped", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + for (const window of [ + { width: 1440, height: 900 }, + { width: 390, height: 844 }, + ]) + test(`reads as stopped once Stop is pressed and when the conversation is opened again, in ${engine}, ${theme}, ${window.width}px`, async () => { + stored = []; + gated = 0; + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const name = (moment: string) => + `stopped-command-${moment}-${engine}-${theme}-${window.width}`; + try { + await page.goto(`${origin}/channel/${CONVERSATION}?theme=${theme}`); + const box = page.getByRole("textbox", { name: "Message" }); + await box.waitFor({ timeout: 15_000 }); + await style(page); + await box.click(); + await page.keyboard.type(ASKED); + await page.getByRole("button", { name: "Send message" }).click(); + + // Under way: the line says so and shimmers, and Stop is offered. + await page + .getByText("Running a command") + .first() + .waitFor({ timeout: 30_000 }); + expect((await readLine(page)).shimmers).toBe(1); + await shoot(page, name("running")); + + const stop = page.getByRole("button", { name: "Stop the Bot" }); + await stop.click(); + await stop.waitFor({ state: "detached", timeout: 15_000 }); + await shoot(page, name("stopped")); + await expectStopped(page); + await shoot(page, name("stopped-open")); + + // Opened again, with the runtime's answer for the stopped step in the thread. + stored = thread(stored.slice(0, 1), RUNTIME_STOPPED); + await page.reload(); + await commandLine(page).waitFor({ timeout: 30_000 }); + await shoot(page, name("reopened")); + await expectStopped(page); + await shoot(page, name("reopened-open")); + + // And with no answer for it at all. + stored = thread(stored.slice(0, 1)); + await page.reload(); + await expectStopped(page); + + // The page never ran the command itself. + expect(gated).toBe(0); + } finally { + await page.close(); + } + }, 120_000); +}); diff --git a/app/tests/stopped-command-step.test.tsx b/app/tests/stopped-command-step.test.tsx new file mode 100644 index 0000000000..53805eb7a0 --- /dev/null +++ b/app/tests/stopped-command-step.test.tsx @@ -0,0 +1,108 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, fireEvent, render } from "@testing-library/react"; +import type { VisibleChatItem } from "../src/components/channels/chat-messages"; +import { + ToolActivity, + type ToolGroup, +} from "../src/components/channels/tool-activity"; +import { TurnInFlightContext } from "../src/components/gallery/streaming"; + +/* + * A command the person stopped, as one row of a folded run of the Bot's steps. Found on 2026-11-30: + * Stop pressed while a Bot ran a command, and the command still read "Running a command" once the + * Bot had stopped. A row says "Not completed" for a step its stopped turn left with no answer, and a + * command's row named it "Running a command" beside that. Opened again, the runtime's own answer for + * the stopped step (`{ status: "stopped", ... }`) read as a command that didn't work. + * stopped-command-layout.test.tsx drives the same Stop in a real browser, on the command's own line. + */ +beforeAll(() => GlobalRegistrator.register()); +afterEach(cleanup); +afterAll(() => GlobalRegistrator.unregister()); + +type ToolItem = Extract; + +const BUILD = "pdflatex -interaction=nonstopmode report.tex"; +/** What the runtime answers a step its run was stopped under with, as the thread keeps it. */ +const RUNTIME_STOPPED = JSON.stringify({ + status: "stopped", + reason: "stop_requested", + message: "Run stopped by user", +}); + +function command(id: string, line: string, result?: string): ToolItem { + return { + kind: "tool", + id, + toolCall: { + id, + type: "function", + function: { + name: "computer_run_command", + arguments: JSON.stringify({ command: line }), + }, + }, + ...(result === undefined ? {} : { result }), + }; +} + +/** + * Two commands: one that ran, and the build, answered or not. The turn going, they are the newest + * row. Opened, as the person opens it. + */ +function steps(build: string | undefined, turn: "going" | "over") { + const view = render( + + + + + , + ); + for (const summary of view.container.querySelectorAll("summary")) + fireEvent.click(summary); + return view.container.textContent ?? ""; +} + +test("a command its stopped turn left with no answer reads as not completed, never as running", () => { + const text = steps(undefined, "over"); + expect(text).toContain("Run a command"); + expect(text).toContain("Not completed"); + expect(text).not.toContain("Running"); +}); + +test("the runtime's answer for a command its run was stopped under reads the same, not as a failure", () => { + const text = steps(RUNTIME_STOPPED, "over"); + expect(text).toContain("Run a command"); + expect(text).toContain("Not completed"); + expect(text).not.toContain("Didn't work"); + expect(text).not.toContain("Run stopped by user"); + expect(text).not.toContain("Running"); +}); + +test("while its turn is still going, a command with no answer is running", () => { + const text = steps(undefined, "going"); + expect(text).toContain("Running a command"); + expect(text).toContain("In progress"); + expect(text).not.toContain("Not completed"); +}); From a0c8b9d1c25b83913dca279bf942ddf162134019 Mon Sep 17 00:00:00 2001 From: Sam Julien Date: Mon, 30 Nov 2026 14:39:35 -0800 Subject: [PATCH 005/224] Fix Home animation and dropdowns at window zoom (#2226) * fix: keep Home and settings selects usable at zoom * test: allow for browser contention in Theme menu checks * test: stabilize wheel scrolling in the zoomed Theme menu * Keep Home's field full size and running to the top at zoom With #2498 the field's canvas fills the pane, so the hard top edge this branch set out to fix is gone on main at every zoom. The shader's fit-to-room radius and edge fade then shrank the orb in OpenBot Desktop's smallest window at 100% and drew nothing at 200%, and faded the glow out before the top. Drop them and keep the canvas-coordinate fix. A browser test shoots the strip along the window's top, with and without the field, at 150% and 200%, light and dark, in Chromium and WebKit. Also a changelog line for the Theme menu. * Theme menu: flip first, then slide into view only when neither side fits side: "shift" turned off flipping, so with the Theme row near the bottom of an ordinary window the menu slid up over its own trigger instead of opening above it, as it does on main. sticky keeps Base UI's flip and adds the shift along the side axis after it, so the menu opens above or below as before and only slides over the trigger when neither side has room for all three choices. A browser test pins the menu opening above the trigger near the window's bottom. --------- Co-authored-by: David McKay --- CHANGELOG.md | 3 + app/src/components/home/home-field.tsx | 14 +-- app/src/components/settings/theme-row.tsx | 8 +- app/src/components/ui/select.tsx | 9 +- app/tests/home-field-component.test.tsx | 42 ++++++++- app/tests/home-holds-still.test.tsx | 99 ++++++++++++++++++++++ app/tests/theme-follows-system.fixture.tsx | 7 +- app/tests/theme-follows-system.test.tsx | 97 ++++++++++++++++++++- 8 files changed, 267 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90a9428deb..2e3f68f87f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **The Theme menu shows Light, Dark and System in a short window.** With little room above and + below the Theme setting, as in a small or zoomed-in window, the menu cut off Dark. It now moves + up or down to show all three, and scrolls when the window is too short for them. - **Text in Figtree, in every app.** The web app, OpenBot Desktop and the browser extension set their text in Figtree instead of Inter, at the same sizes. Figtree has Latin letters only: Cyrillic, Greek and other scripts are drawn in the computer's own face. diff --git a/app/src/components/home/home-field.tsx b/app/src/components/home/home-field.tsx index 0a1e3f08d8..8a928ecd76 100644 --- a/app/src/components/home/home-field.tsx +++ b/app/src/components/home/home-field.tsx @@ -148,21 +148,25 @@ export function HomeField({ const dpr = Math.min(2, window.devicePixelRatio || 1); const width = Math.round(canvas.clientWidth * dpr); const height = Math.round(canvas.clientHeight * dpr); + const c = canvas.getBoundingClientRect(); + if (!width || !height || !c.width || !c.height) return; if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; } - const c = canvas.getBoundingClientRect(); const b = box().getBoundingClientRect(); + // DOM rectangles and the canvas backing store can scale differently at page zoom. + const scaleX = width / c.width; + const scaleY = height / c.height; gl.viewport(0, 0, width, height); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.uniform4f( uniform("uBox"), - (b.left - c.left) * dpr, - (c.bottom - b.bottom) * dpr, - b.width * dpr, - b.height * dpr, + (b.left - c.left) * scaleX, + (c.bottom - b.bottom) * scaleY, + b.width * scaleX, + b.height * scaleY, ); gl.uniform1f(uniform("uTime"), clock); gl.uniform1f(uniform("uEnergy"), energy); diff --git a/app/src/components/settings/theme-row.tsx b/app/src/components/settings/theme-row.tsx index bcd1f78d2f..381073fb69 100644 --- a/app/src/components/settings/theme-row.tsx +++ b/app/src/components/settings/theme-row.tsx @@ -52,8 +52,12 @@ export function ThemeRow() { {THEME_NAMES[theme]} - {/* Under the trigger and inside the row's right edge, as the Skin menu is. */} - + {/* + * Under the trigger, or over it when there is more room there, as the Skin menu is. Where + * neither side has room for all three choices (a short or zoomed-in window), `sticky` + * slides the menu over the trigger to keep them in view instead of cutting Dark off. + */} + {THEME_PREFERENCES.map((choice) => ( {THEME_NAMES[choice]} diff --git a/app/src/components/ui/select.tsx b/app/src/components/ui/select.tsx index ede9251ea6..7d9fe6b2f0 100644 --- a/app/src/components/ui/select.tsx +++ b/app/src/components/ui/select.tsx @@ -66,11 +66,17 @@ function SelectContent({ align = "center", alignOffset = 0, alignItemWithTrigger = true, + sticky, ...props }: SelectPrimitive.Popup.Props & Pick< SelectPrimitive.Positioner.Props, - "align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger" + | "align" + | "alignOffset" + | "side" + | "sideOffset" + | "alignItemWithTrigger" + | "sticky" >) { return ( @@ -80,6 +86,7 @@ function SelectContent({ align={align} alignOffset={alignOffset} alignItemWithTrigger={alignItemWithTrigger} + sticky={sticky} className="isolate z-50" > { * here: a canvas hands back the same context every time, and once that context is lost it makes * nothing more. */ -function fakeWebGl() { +function fakeWebGl(onBox?: (box: number[]) => void) { let lost = false; const gl = new Proxy( {}, { get(_, name: string) { + if (name === "getUniformLocation") + return (_: unknown, key: string) => key; + if (name === "uniform4f") + return (key: string, ...values: number[]) => { + if (key === "uBox") onBox?.(values); + }; if (name === "getExtension") return (ext: string) => ext === "WEBGL_lose_context" @@ -105,6 +111,40 @@ test("React mounting the field twice, as it does in development, still draws it" } }); +test("the field stays centered on the composer when DOM bounds are zoomed", async () => { + const originalContext = HTMLCanvasElement.prototype.getContext; + const originalRect = HTMLElement.prototype.getBoundingClientRect; + const drawn = Promise.withResolvers(); + const gl = fakeWebGl(drawn.resolve); + HTMLCanvasElement.prototype.getContext = ((): unknown => + gl) as typeof originalContext; + HTMLElement.prototype.getBoundingClientRect = function () { + if (this instanceof HTMLCanvasElement) return new DOMRect(0, 0, 1000, 500); + if (this.getAttribute("data-slot") === "composer") + return new DOMRect(250, 125, 500, 125); + return originalRect.call(this); + }; + try { + const view = render(); + const canvas = view.container.querySelector("canvas"); + if (!canvas) throw new Error("No Home field canvas"); + Object.defineProperties(canvas, { + clientWidth: { value: 800 }, + clientHeight: { value: 400 }, + }); + const [x, y, width, height] = await drawn.promise; + expect([x, y, width, height]).toEqual([ + canvas.width / 4, + canvas.height / 2, + canvas.width / 2, + canvas.height / 4, + ]); + } finally { + HTMLElement.prototype.getBoundingClientRect = originalRect; + HTMLCanvasElement.prototype.getContext = originalContext; + } +}); + /* A visit of its own: the other Home tests in this run have had theirs. */ const visit = createHomeIntro( (() => { diff --git a/app/tests/home-holds-still.test.tsx b/app/tests/home-holds-still.test.tsx index 94b81046ed..a36ffe4cf8 100644 --- a/app/tests/home-holds-still.test.tsx +++ b/app/tests/home-holds-still.test.tsx @@ -346,12 +346,14 @@ async function open( width?: number; height?: number; reducedMotion?: "reduce" | "no-preference"; + deviceScaleFactor?: number; } = {}, ): Promise { const browser = browsers.get(engine); if (!browser) throw new Error(`no ${engine}`); const page = await browser.newPage({ viewport: { width: look.width ?? 1280, height: look.height ?? 800 }, + deviceScaleFactor: look.deviceScaleFactor ?? 1, colorScheme: theme, reducedMotion: look.reducedMotion ?? "reduce", }); @@ -658,3 +660,100 @@ describe.skipIf(!asked)("Home while it loads", () => { }, 60_000); } }); + +/** + * How far two screenshots of the same strip differ, as the mean of each pixel's color change on a + * 0-255 scale. Decoded by the page itself, which has the image decoder the test runner lacks. + */ +function meanDifference(page: Page, a: Buffer, b: Buffer): Promise { + return page.evaluate( + async ([one, two]) => { + const pixels = async (src: string) => { + const image = new Image(); + image.src = src; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + if (!context) throw new Error("no 2d context"); + context.drawImage(image, 0, 0); + return context.getImageData(0, 0, canvas.width, canvas.height).data; + }; + const [p, q] = await Promise.all([pixels(one), pixels(two)]); + let sum = 0; + for (let at = 0; at < p.length; at += 4) + for (let channel = 0; channel < 3; channel += 1) + sum += Math.abs((p[at + channel] ?? 0) - (q[at + channel] ?? 0)); + return sum / ((p.length / 4) * 3); + }, + [ + `data:image/png;base64,${a.toString("base64")}`, + `data:image/png;base64,${b.toString("base64")}`, + ] as const, + ); +} + +/** + * The glow and dot rings behind Home's box reach the top of the window at every zoom. + * + * Home's field once stopped 80px below the top with a hard edge (#2498 let it run to the top). A + * zoom fix then sized and faded the field to fit the room around the box, which in OpenBot + * Desktop's smallest window (1340x560 points) shrank it at 100% and drew nothing at all at 200%. + * A window zoomed in is a viewport of fewer CSS pixels, each drawn with more device pixels, as + * page zoom does. The strip along the window's top, between the sidebar toggle and the business + * link, is shot with the field and without it: the field must show there. + */ +describe.skipIf(!asked)("Home's field at zoom", () => { + const WINDOW = { width: 1340, height: 560 }; + for (const engine of engines) + for (const theme of THEMES) + for (const zoom of [1.5, 2]) { + test(`reaches the window's top at ${zoom * 100}%, in ${engine}, ${theme}`, async () => { + const width = Math.round(WINDOW.width / zoom); + const { page } = await loaded( + engine, + theme, + "personal", + "later", + undefined, + { + width, + height: Math.round(WINDOW.height / zoom), + deviceScaleFactor: zoom, + }, + ); + try { + await page + .locator('[data-slot="home-field"] canvas:not([hidden])') + .waitFor(); + // The field draws on the next frame after the page settles. + await page.evaluate( + () => + new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ), + ); + const clip = { + x: width * 0.3, + y: 0, + width: width * 0.4, + height: 12, + }; + const withField = await page.screenshot({ clip }); + await page.evaluate(() => { + const field = document.querySelector( + '[data-slot="home-field"]', + ); + if (field) field.style.visibility = "hidden"; + }); + const without = await page.screenshot({ clip }); + expect( + await meanDifference(page, withField, without), + ).toBeGreaterThan(1); + } finally { + await page.close(); + } + }, 60_000); + } +}); diff --git a/app/tests/theme-follows-system.fixture.tsx b/app/tests/theme-follows-system.fixture.tsx index 39eda50555..46ad202a87 100644 --- a/app/tests/theme-follows-system.fixture.tsx +++ b/app/tests/theme-follows-system.fixture.tsx @@ -1,4 +1,5 @@ import { createRoot } from "react-dom/client"; +import { ThemeRow } from "@/components/settings/theme-row"; import { ThemeProvider, useTheme } from "@/components/theme-provider"; /** @@ -23,6 +24,10 @@ const root = document.getElementById("root"); if (!root) throw new Error("no #root"); createRoot(root).render( - + {new URLSearchParams(location.search).has("menu") ? ( + + ) : ( + + )} , ); diff --git a/app/tests/theme-follows-system.test.tsx b/app/tests/theme-follows-system.test.tsx index deb0c541f1..faede6b14c 100644 --- a/app/tests/theme-follows-system.test.tsx +++ b/app/tests/theme-follows-system.test.tsx @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import type { Browser, Page } from "playwright-core"; +import { compile } from "tailwindcss"; /** * OpenBot follows the system's light or dark until a person chooses one of their own. @@ -26,6 +27,7 @@ const LEGACY_KEY = "openbot-theme"; let browser: Browser; let script: string; +let menuCss: string; /** The app's page, with the fixture in the app's place and a note of the theme at first paint. */ let html: string; @@ -50,6 +52,18 @@ beforeAll(async () => { .replace("/src/main.tsx", "/theme.js"); if (!html.includes("__darkAtFirstPaint") || !html.includes("/theme.js")) throw new Error("index.html no longer has the shape this test reads"); + const compiler = await compile( + "@theme { --spacing: 0.25rem; } @tailwind utilities;", + ); + // Include the portaled options and scroll arrows before the menu first measures itself. + const classes = [ + "components/settings/theme-row.tsx", + "components/ui/item.tsx", + "components/ui/select.tsx", + ].flatMap((file) => + readFileSync(join(APP, "src", file), "utf8").split(/[\s"'`{}]+/), + ); + menuCss = compiler.build(classes); const { chromium } = await import("playwright-core"); // The CI job installs full Chromium without the headless shell. browser = await chromium.launch({ channel: "chromium" }); @@ -64,6 +78,7 @@ async function open( system: "light" | "dark", stored: string | null = null, key = KEY, + menu = false, ): Promise { const context = await browser.newContext({ colorScheme: system }); const page = await context.newPage(); @@ -88,11 +103,89 @@ async function open( [key, stored] as const, ); } - await page.goto(`${ORIGIN}/`); - await page.locator("[data-setting-shows]").waitFor({ timeout: 8000 }); + await page.goto(`${ORIGIN}/${menu ? "?menu" : ""}`); + await (menu + ? page.getByRole("combobox", { name: "Theme" }) + : page.locator("[data-setting-shows]") + ).waitFor({ timeout: 8000 }); return page; } +test.skipIf(!asked).each([ + [160, true], + [80, false], +] as const)( + "the Theme menu reaches Dark at %dpx viewport height", + async (height, fits) => { + const page = await open("light", null, KEY, true); + try { + await page.setViewportSize({ width: 640, height }); + await page.addStyleTag({ + content: `${menuCss}\nhtml { zoom: 1.25 } body { margin: 0 } #root { padding-top: ${fits ? 36 : 12}px }`, + }); + const trigger = page.getByRole("combobox", { name: "Theme" }); + await trigger.click(); + const list = page.getByRole("listbox"); + await list.waitFor(); + if (!fits) { + await page.locator('[data-slot="select-scroll-down-button"]').waitFor(); + await list.hover(); + } + const dimensions = await list.evaluate((menu) => [ + menu.clientHeight, + menu.scrollHeight, + ]); + if (fits) { + expect(dimensions[0]).toBe(dimensions[1]); + } else { + expect(dimensions[0]).toBeLessThan(dimensions[1]); + await page.mouse.wheel(0, 100); + await page.waitForFunction( + () => + (document.querySelector('[role="listbox"]')?.scrollTop ?? 0) > 0, + null, + { timeout: 3000 }, + ); + } + await list.getByRole("option", { name: "Dark" }).click(); + expect( + await trigger.locator('[data-slot="select-value"]').textContent(), + ).toBe("Dark"); + } finally { + await page.context().close(); + } + }, + 30_000, +); + +// With room above and not below, the menu opens above the trigger rather than sliding over it. +test.skipIf(!asked)( + "the Theme menu opens above the trigger near the window's bottom", + async () => { + const page = await open("light", null, KEY, true); + try { + await page.setViewportSize({ width: 640, height: 400 }); + await page.addStyleTag({ + content: `${menuCss}\nbody { margin: 0 } #root { padding-top: 340px }`, + }); + const trigger = page.getByRole("combobox", { name: "Theme" }); + await trigger.click(); + const list = page.getByRole("listbox"); + await list.waitFor(); + const box = await trigger.boundingBox(); + const popup = await page + .locator('[data-slot="select-content"]') + .boundingBox(); + if (!box || !popup) throw new Error("the Theme menu didn't open"); + expect(popup.y + popup.height).toBeLessThanOrEqual(box.y + 0.5); + expect(await list.getByRole("option").count()).toBe(3); + } finally { + await page.context().close(); + } + }, + 30_000, +); + /** What the page shows: the theme at first paint, the theme now, and what the setting reads. */ function shown(page: Page) { return page.evaluate( From cff1b15e443001e9dfc3577497a8f96a80b7e047 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 14:49:22 -0800 Subject: [PATCH 006/224] Show a picture a Bot makes as a card in the conversation (#2519) * Draw a picture a Bot makes as a card in the conversation A generate_image call now draws a card of its own, built like the card a sent file draws: the same border, fill and corners, the same lightbox and the same Download button. While the picture is being made, the card is already there at the shape the Bot asked for, painted in frame first, with the prompt and "Making the image". When the answer comes, the picture fades in inside the same box, with what was asked for, the model and the size, and Download saving it under its stored name. On a person's first picture, when other image models are available, one quiet line names them and says they can ask for one by name. When no picture was made, the card says why in plain words: the provider wanting the organization verified (with a link to do it), an image limit used up (with when it resets, in the person's own time, and the plan's page), a refusal, a failure, no image model, an unknown model, a picture too large to keep. A call whose turn ended without an answer says it stopped instead of making forever. The card is drawn from the stored answer alone, so a reload and a task's thread show the same card. The picture's name in the Bot's words downloads it, as a sent file's does. shared/generate-image.ts is the tool's contract as the contract change defines it, carried here until that change lands. * Run the picture card's browser test with the other Chromium files in CI * Keep the picture card to the app's corner steps, and allow its one timed paint-in wait * Serve the app's own font to the picture card's browser test --- .github/workflows/ci.yml | 5 +- .../components/channels/attachment-view.tsx | 8 +- .../components/channels/chat-transcript.tsx | 13 +- .../channels/generated-image-card.tsx | 518 ++++++++++++++++++ app/src/lib/copilot/generate-image-tool.tsx | 76 +++ app/src/lib/copilot/provider.tsx | 3 + app/src/styles.css | 34 ++ app/tests/generated-image-browser.data.ts | 27 + app/tests/generated-image-browser.fixture.tsx | 231 ++++++++ app/tests/generated-image-browser.test.tsx | 486 ++++++++++++++++ app/tests/generated-image-card.test.tsx | 400 ++++++++++++++ app/tests/no-fixed-settle-waits.test.ts | 4 + 12 files changed, 1800 insertions(+), 5 deletions(-) create mode 100644 app/src/components/channels/generated-image-card.tsx create mode 100644 app/src/lib/copilot/generate-image-tool.tsx create mode 100644 app/tests/generated-image-browser.data.ts create mode 100644 app/tests/generated-image-browser.fixture.tsx create mode 100644 app/tests/generated-image-browser.test.tsx create mode 100644 app/tests/generated-image-card.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e5e25abcb6..526fe0c9dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -380,7 +380,8 @@ jobs: # held at Connect your AI until they connect their own, and Admin's Providers where an admin # changes, disconnects and connects the organization's AI, told apart from their own, and # People's Remove dialog and the SCIM row fitting wide and on a phone, and an unsent reply and - # its files staying with their conversation across a switch and a reload. The + # its files staying with their conversation across a switch and a reload, and a picture a Bot + # made drawn as the sent file's card is, in every state, opening full size. The # onboarding frame reads the generated app config, which `bun test` alone doesn't write (the # test script's pretest does). - run: bun run generate:app-config @@ -390,7 +391,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel app/tests/tool-line-reduced-motion.test.tsx app/tests/onboarding-window-buttons.test.tsx app/tests/onboarding-orb-room.test.tsx app/tests/transcript-rail-clearance.test.tsx app/tests/a2ui-frame.test.tsx app/tests/update-banner-layout.test.tsx app/tests/composer-dictation-notice-layout.test.tsx app/tests/conversation-intro-halo.test.tsx app/tests/transcript-room.test.tsx app/tests/skins-window-buttons.test.tsx app/tests/opendots-rail-badge.test.tsx app/tests/account-version-layout.test.tsx app/tests/organization-menu-names.test.tsx app/tests/bot-orb-one-color.test.tsx app/tests/compact-avatar-layout.test.tsx app/tests/theme-follows-system.test.tsx app/tests/desktop-window-theme.test.tsx app/tests/bot-screen-record-layout.test.tsx app/tests/teams-screens-layout.test.tsx app/tests/team-grants-screens-layout.test.tsx app/tests/team-models-screens-layout.test.tsx app/tests/conversation-refusal-layout.test.tsx app/tests/model-picker-phone-layout.test.tsx app/tests/needs-you-board-layout.test.tsx app/tests/checkbox-contrast.test.tsx app/tests/maths-rendering.test.tsx app/tests/task-report-chip.test.tsx app/tests/consent-handoff.test.tsx app/tests/large-picture-tile.test.tsx app/tests/audit-computer-limit-layout.test.tsx app/tests/ai-connection-dialog.test.tsx app/tests/connect-your-ai.test.tsx app/tests/admin-providers-connection.test.tsx app/tests/admin-people-remove-layout.test.tsx app/tests/composer-keeps-draft-browser.test.tsx + bun test --parallel app/tests/tool-line-reduced-motion.test.tsx app/tests/onboarding-window-buttons.test.tsx app/tests/onboarding-orb-room.test.tsx app/tests/transcript-rail-clearance.test.tsx app/tests/a2ui-frame.test.tsx app/tests/update-banner-layout.test.tsx app/tests/composer-dictation-notice-layout.test.tsx app/tests/conversation-intro-halo.test.tsx app/tests/transcript-room.test.tsx app/tests/skins-window-buttons.test.tsx app/tests/opendots-rail-badge.test.tsx app/tests/account-version-layout.test.tsx app/tests/organization-menu-names.test.tsx app/tests/bot-orb-one-color.test.tsx app/tests/compact-avatar-layout.test.tsx app/tests/theme-follows-system.test.tsx app/tests/desktop-window-theme.test.tsx app/tests/bot-screen-record-layout.test.tsx app/tests/teams-screens-layout.test.tsx app/tests/team-grants-screens-layout.test.tsx app/tests/team-models-screens-layout.test.tsx app/tests/conversation-refusal-layout.test.tsx app/tests/model-picker-phone-layout.test.tsx app/tests/needs-you-board-layout.test.tsx app/tests/checkbox-contrast.test.tsx app/tests/maths-rendering.test.tsx app/tests/task-report-chip.test.tsx app/tests/consent-handoff.test.tsx app/tests/large-picture-tile.test.tsx app/tests/audit-computer-limit-layout.test.tsx app/tests/ai-connection-dialog.test.tsx app/tests/connect-your-ai.test.tsx app/tests/admin-providers-connection.test.tsx app/tests/admin-people-remove-layout.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/generated-image-browser.test.tsx # Dictation in the Desktop window on a Mac whose recognizer has no English (United Kingdom) on # the device, in Chromium and in WebKit, the engine the Mac window draws with: it listens in the diff --git a/app/src/components/channels/attachment-view.tsx b/app/src/components/channels/attachment-view.tsx index df833241e6..00ec4b7223 100644 --- a/app/src/components/channels/attachment-view.tsx +++ b/app/src/components/channels/attachment-view.tsx @@ -111,6 +111,7 @@ export function AttachmentLightbox({ filename, url, trigger, + rounded, }: { children: React.ReactNode; filename?: string; @@ -121,6 +122,11 @@ export function AttachmentLightbox({ * is fetched only once somebody opens it. */ trigger?: React.ReactElement; + /** + * The thumbnail's corners, when they are not its own: a picture that fills a card to its edges + * takes the card's corners, so it is square where it meets the caption under it. + */ + rounded?: string; }) { const label = filename ?? "Attachment"; /* @@ -139,7 +145,7 @@ export function AttachmentLightbox({ className={ trigger ? undefined - : "block cursor-zoom-in overflow-hidden rounded-xl" + : `block cursor-zoom-in overflow-hidden ${rounded ?? "rounded-xl"}` } render={ trigger ?? + ) : null} + + {result?.otherModels?.length ? ( +

+ + + You can also ask for{" "} + {orList(result.otherModels.map((model) => model.label))} by name. + +

+ ) : null} + + ); +} + +/** No picture: what happened in plain words, and where to fix it when there is a place to. */ +function NotMade({ + heading, + message, + prompt, + fixUrl, + fixLabel, + resets = null, + tone, +}: { + heading: string; + message: string; + prompt?: string; + fixUrl?: string; + /** What the link says; "Open " when the reason has no words of its own. */ + fixLabel?: string; + /** When an image limit ends, in words (`resetsWhen`), or null when nobody said. */ + resets?: string | null; + tone: "muted" | "destructive"; +}) { + let host = ""; + try { + host = fixUrl ? new URL(fixUrl).hostname : ""; + } catch { + host = ""; + } + return ( +
+
+ + + + + {heading} + + {message} + + {resets ? ( + + It resets {resets}. + + ) : null} + {prompt ? ( + + Asked for: {prompt} + + ) : null} + +
+ {fixUrl && host ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/app/src/lib/copilot/generate-image-tool.tsx b/app/src/lib/copilot/generate-image-tool.tsx new file mode 100644 index 0000000000..46707d2249 --- /dev/null +++ b/app/src/lib/copilot/generate-image-tool.tsx @@ -0,0 +1,76 @@ +import { useRenderTool } from "@copilotkit/react-core/v2"; +import { + GENERATE_IMAGE_TOOL, + type ImageAspect, + parseGenerateImageResult, +} from "@openbot/shared/generate-image"; +import { useContext } from "react"; +import { z } from "zod"; +import { GeneratedImageCard } from "@/components/channels/generated-image-card"; +import { TurnInFlightContext } from "@/components/gallery/streaming"; +import { readOutcome } from "@/lib/computers/activity"; + +/** + * How a Bot making a picture reads in the conversation: the picture card (`GeneratedImageCard`). + * + * RENDER ONLY. `generate_image` runs on the server for every Bot, built-in or connected over AG-UI, + * which stores the picture as a file of the conversation and answers with it. Nothing here registers + * a tool or decides anything; the card is drawn from the call's arguments while it runs and from its + * stored answer once there is one, so a reload draws the same card. + */ +const parameters = z.object({ + prompt: z.string().optional(), + aspect: z.enum(["square", "portrait", "landscape"]).optional(), + editOf: z.string().optional(), + model: z.string().optional(), +}); + +/** One call, as its card. A component, so it can read whether its turn is still running. */ +export function GenerateImageCall({ + prompt, + aspect, + result, +}: { + prompt?: string; + aspect?: ImageAspect; + result?: unknown; +}) { + const turnRunning = useContext(TurnInFlightContext); + const parsed = result === undefined ? null : parseGenerateImageResult(result); + /* + * An answer that is not this tool's: the runtime closing a call its run ended under, in its own + * words (`readOutcome` reads those). A stand-in that says the answer is still on its way + * (`readOutcome` gives null) is no answer yet. + */ + const outcome = parsed ? null : readOutcome(result); + const answered = parsed !== null || outcome !== null; + const closedWith = outcome + ? (typeof outcome.reason === "string" && outcome.reason.trim()) || + "The answer couldn't be read." + : undefined; + return ( + + ); +} + +export function GenerateImageTool() { + useRenderTool({ + name: GENERATE_IMAGE_TOOL, + parameters, + render: ({ parameters: given, result }) => ( + + ), + }); + return null; +} diff --git a/app/src/lib/copilot/provider.tsx b/app/src/lib/copilot/provider.tsx index 8e0b797814..bbe4976923 100644 --- a/app/src/lib/copilot/provider.tsx +++ b/app/src/lib/copilot/provider.tsx @@ -20,6 +20,7 @@ import { CodingTools } from "./coding-tools"; import { ComputerTools } from "./computer-tools"; import { EscalationTool } from "./escalation-tool"; import { GalleryTools } from "./gallery-tools"; +import { GenerateImageTool } from "./generate-image-tool"; import { GENERATIVE_UI_DESIGN_SKILL } from "./generative-ui"; import { HandoffTool } from "./handoff-tool"; import { OrchestrationTools } from "./orchestration-tools"; @@ -100,6 +101,8 @@ export function CopilotProvider({ children }: { children: ReactNode }) { {/* A Bot offering a check-in on what the two of them just looked at. Runs on the server. */} + {/* A Bot making a picture: its card, from the call and its stored answer. Runs on the server. */} + {/* A coding harness Bot's own tools, which it runs itself: commands, diffs and its plan. */} {/* Gallery tools are registered once; their handlers ask about the Bot that made the call (see botOfCall). */} diff --git a/app/src/styles.css b/app/src/styles.css index 8c4484826a..9c7fabc78c 100644 --- a/app/src/styles.css +++ b/app/src/styles.css @@ -131,6 +131,40 @@ } } +/* + * Where a picture a Bot is making will be (`GeneratedImageCard`): a wide, soft band of light crosses + * the muted placeholder on a slow diagonal, so the card reads as being painted, not stuck. The band + * is the foreground at a low strength, so it shows on the muted fill in either theme. Reduced motion + * leaves the placeholder still. + */ +.image-painting { + background-image: linear-gradient( + 115deg, + transparent 30%, + color-mix(in oklch, var(--foreground) 7%, transparent) 50%, + transparent 70% + ); + background-size: 250% 100%; + background-repeat: no-repeat; + animation: image-painting 2.4s linear infinite; +} + +@keyframes image-painting { + from { + background-position: 100% 0; + } + to { + background-position: 0% 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .image-painting { + animation: none; + background-image: none; + } +} + /* * A progress bar with no value (``): something is under way and nothing knows * how far it has got, such as a Bot's computer starting. A short segment travels the track and goes diff --git a/app/tests/generated-image-browser.data.ts b/app/tests/generated-image-browser.data.ts new file mode 100644 index 0000000000..3b6c86d1a9 --- /dev/null +++ b/app/tests/generated-image-browser.data.ts @@ -0,0 +1,27 @@ +/** + * The pictures generated-image-browser.fixture.tsx draws and generated-image-browser.test.tsx serves, + * shared so the page and the server agree on each one's address, name and size. + */ +export const PICTURES = { + chart: { + id: "0c6a3f2e-9b14-4d8e-a1f7-3e5b2c9d8a01", + name: "q3-revenue.png", + width: 1200, + height: 800, + sizeBytes: 182_311, + }, + logo: { + id: "5b0e6f1c-1a2b-4c3d-8e9f-0a1b2c3d4e5f", + name: "retro-teal-offsite-logo.png", + width: 1024, + height: 1024, + sizeBytes: 1_482_113, + }, + banner: { + id: "8d2f4a6b-3c5e-4f70-9a1b-2c3d4e5f6a7b", + name: "offsite-event-banner.png", + width: 1536, + height: 1024, + sizeBytes: 2_104_557, + }, +} as const; diff --git a/app/tests/generated-image-browser.fixture.tsx b/app/tests/generated-image-browser.fixture.tsx new file mode 100644 index 0000000000..f52365e202 --- /dev/null +++ b/app/tests/generated-image-browser.fixture.tsx @@ -0,0 +1,231 @@ +import type { Message } from "@ag-ui/core"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GENERATE_IMAGE_TOOL } from "@openbot/shared/generate-image"; +import { SEND_FILE_TOOL } from "@openbot/shared/send-file"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { ComputerTools } from "@/lib/copilot/computer-tools"; +import { GenerateImageTool } from "@/lib/copilot/generate-image-tool"; +import { readableTurns } from "@/lib/copilot/thread-messages"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import { PICTURES } from "./generated-image-browser.data"; + +/** + * A conversation in which a Bot sent a chart from its computer and then made pictures, as it is drawn + * when opened again, for generated-image-browser.test.tsx to bundle and load in a real browser. Every + * state of the picture card is here, beside the sent file's card the app already draws: made (a + * person's first picture, naming the other models), made again (landscape), the provider asking for + * verification, a refusal, a failure, and a portrait still being made in the turn that is running. + * + * The turns are in the history store's own dialect and read through `readableTurns`, as a reload + * reads them. `?only=making` draws only the turn still being made, for its paint-in. + */ +setCurrentOrganization("default"); + +const only = new URLSearchParams(location.search).get("only"); + +let turn = 0; +function call( + ask: string, + name: string, + args: Record, + answer: unknown, + said?: string, +): unknown[] { + turn += 1; + const id = `call_${turn}`; + return [ + { id: `u${turn}`, role: "user", content: ask }, + { + id: `a${turn}`, + role: "assistant", + content: null, + toolCalls: [{ id, name, args }], + }, + ...(answer === undefined + ? [] + : [ + { + id: `r${turn}`, + role: "tool", + toolCallId: id, + content: JSON.stringify(answer), + }, + ]), + ...(said ? [{ id: `s${turn}`, role: "assistant", content: said }] : []), + ]; +} + +const picture = (key: keyof typeof PICTURES) => { + const { id, name, width, height, sizeBytes } = PICTURES[key]; + return { + attachmentId: id, + name, + mimeType: "image/png", + sizeBytes, + url: `/api/attachments/${id}`, + width, + height, + }; +}; + +const GPT = { id: "gpt-image-2", label: "GPT Image 2", vendor: "openai" }; +const LOGO_PROMPT = + "A retro logo for our team offsite: a cream sun setting over teal hills, the words OFFSITE 2026 in a rounded serif"; +const BANNER_PROMPT = + "A wide banner of the same logo for the event page, more sky, the sun low on the left"; +const POSTER_PROMPT = + "A tall poster for the offsite's evening, teal sky, string lights over a long table"; + +const making = call( + "And a tall poster for the evening?", + GENERATE_IMAGE_TOOL, + { prompt: POSTER_PROMPT, aspect: "portrait" }, + undefined, +); + +const stored: unknown[] = + only === "making" + ? making + : [ + ...call( + "Send me the Q3 revenue chart you made.", + SEND_FILE_TOOL, + { path: "charts/q3-revenue.png" }, + { + ok: true, + file: { + attachmentId: PICTURES.chart.id, + name: PICTURES.chart.name, + mimeType: "image/png", + sizeBytes: PICTURES.chart.sizeBytes, + url: `/api/attachments/${PICTURES.chart.id}`, + }, + }, + "Here's the Q3 chart.", + ), + ...call( + "Make a logo for our offsite, retro, teal.", + GENERATE_IMAGE_TOOL, + { prompt: LOGO_PROMPT }, + { + ok: true, + image: picture("logo"), + model: GPT, + prompt: LOGO_PROMPT, + otherModels: [ + { id: "gemini-3.1-flash-image", label: "Nano Banana 2" }, + { id: "grok-imagine", label: "Grok Imagine" }, + ], + }, + "Here's a first take on the offsite logo.", + ), + ...call( + "Make it wider for the event page.", + GENERATE_IMAGE_TOOL, + { + prompt: BANNER_PROMPT, + aspect: "landscape", + editOf: PICTURES.logo.id, + }, + { + ok: true, + image: picture("banner"), + model: GPT, + prompt: BANNER_PROMPT, + }, + ), + ...call( + "Try it with GPT Image 2.5.", + GENERATE_IMAGE_TOOL, + { prompt: LOGO_PROMPT, model: "GPT Image 2.5" }, + { + ok: false, + reason: "needs_verification", + message: + "OpenAI needs your organization verified before it makes pictures. Verify it on OpenAI's site, then ask again.", + fixUrl: "https://platform.openai.com/settings/organization/general", + }, + ), + ...call( + "Put the CEO's face on it.", + GENERATE_IMAGE_TOOL, + { prompt: "The offsite logo with a photo of a real person's face" }, + { + ok: false, + reason: "refused", + message: + "The image model said this prompt goes against its rules. Try describing it differently.", + }, + ), + ...call( + "One more, in black and white.", + GENERATE_IMAGE_TOOL, + { prompt: "The offsite logo in black and white" }, + { + ok: false, + reason: "failed", + message: "OpenAI didn't answer in time. Try again in a moment.", + }, + ), + ...call( + "Make three more variations.", + GENERATE_IMAGE_TOOL, + { prompt: "A variation of the offsite logo with a crescent moon" }, + { + ok: false, + reason: "limit_reached", + message: + "Your ChatGPT plan has made as many pictures as it allows for now.", + resetsAt: new Date( + new Date().getFullYear(), + new Date().getMonth(), + new Date().getDate() + 1, + 9, + 0, + ).toISOString(), + fixUrl: "https://chatgpt.com/#pricing", + }, + ), + ...making, + ]; + +const { messages } = readableTurns(stored); + +function Conversation() { + return ( +
+ +
+ ); +} + +const rootRoute = createRootRoute({ component: Conversation }); +const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ["/"] }), +}); + +const root = document.getElementById("root"); +if (root) { + createRoot(root).render( + + + + + + + + + , + ); +} diff --git a/app/tests/generated-image-browser.test.tsx b/app/tests/generated-image-browser.test.tsx new file mode 100644 index 0000000000..4a5a81add2 --- /dev/null +++ b/app/tests/generated-image-browser.test.tsx @@ -0,0 +1,486 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { PICTURES } from "./generated-image-browser.data"; +import { still } from "./page-still"; + +/** + * The picture card a Bot's `generate_image` call draws, in a real browser, beside the card a file the + * Bot sent already draws: the same corners, border and fill, the picture loaded and opening full + * size, every state fitting the chat column at a phone's width and a desktop's, in both themes. + * + * Drawn from the real transcript, the app's own renderers and its stylesheet, with a conversation + * read the way a reload reads it. The server is played here: each picture is a real PNG, served at + * the conversation's attachment address as the server serves one. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/generated-image-browser.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= the page, each card, the lightbox and the paint-in are saved there. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORIGIN = "http://openbot.test"; +const WIDTHS = [390, 1000] as const; +const THEMES = ["light", "dark"] as const; +type Theme = (typeof THEMES)[number]; +const FILE_READ = /^\/api\/v2\/organizations\/[^/]+\/attachments\/([^/]+)$/; + +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "generated-image-browser.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + // `@/lib/marks` is Vite's `import.meta.glob`, so no brand marks, as in the other browser tests. + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +/* + * The pictures, as real PNGs: each one drawn by the browser at its own size and saved as a + * screenshot, so the card loads, measures and opens a real image of that shape. + */ +const ART: Record = { + logo: `
+
+
+
+
OFFSITE 2026
`, + banner: `
+
+
+
+
OFFSITE
2026
`, + chart: `
Q3 revenue +
+
+
+
`, +}; + +const browsers = new Map(); +const pngs = new Map(); +let script: string; + +beforeAll(async () => { + if (!asked) return; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } + const painter = browsers.values().next().value as Browser; + for (const [key, picture] of Object.entries(PICTURES)) { + const page = await painter.newPage({ + viewport: { width: picture.width, height: picture.height }, + }); + await page.setContent( + `${ART[key as keyof typeof PICTURES]}`, + ); + pngs.set(picture.id, await page.screenshot({ type: "png" })); + await page.close(); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); +}); + +/** Every class now on the page. */ +function classesOn(page: Page): Promise { + return page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ), + ]); +} + +/** Styled for everything now on the page, as the app's build styles it. */ +async function style(page: Page) { + await page.addStyleTag({ content: await stylesheet(await classesOn(page)) }); + await page.evaluate(() => document.fonts.ready); +} + +/** + * Every class the card's source names, in any state. The paint-in is drawn before anything could be + * read off the page, so its stylesheet is built from the source, as Tailwind builds the app's. + */ +function cardClasses(): string[] { + const source = readFileSync( + join(APP, "src", "components", "channels", "generated-image-card.tsx"), + "utf8", + ); + return [...new Set(source.match(/[A-Za-z0-9_:./[\]()%-]+/g) ?? [])]; +} + +async function open( + engine: string, + theme: Theme, + width: number, + options: { + only?: string; + motion?: "reduce" | "no-preference"; + /** A stylesheet in the page from the start, so a paint-in is styled from its first frame. */ + css?: string; + } = {}, +) { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + // Tall enough that the whole conversation is in view, and no control over the cards. + viewport: { width, height: options.only ? 900 : 3200 }, + colorScheme: theme, + reducedMotion: options.motion ?? "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + // How the card being made looks the moment it is put on the page, before anything moves. + await page.addInitScript(() => { + const observer = new MutationObserver(() => { + const card = document.querySelector( + 'figure[aria-label="Making the image"]', + ); + if (!card) return; + observer.disconnect(); + (window as { firstLook?: string }).firstLook = + `${getComputedStyle(card).borderTopStyle} ${card.querySelector(".image-painting") ? "painting" : "placeholder"}`; + }); + observer.observe(document, { childList: true, subtree: true }); + }); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + await page.route(`${ORIGIN}/**`, async (route) => { + const path = new URL(route.request().url()).pathname; + if (path === "/transcript.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return route.fulfill({ path: font }); + // A stored picture, as the server serves an attachment: its type, and its bytes. + const read = FILE_READ.exec(path); + const png = read ? pngs.get(read[1] ?? "") : undefined; + if (png) + return route.fulfill({ + status: 200, + headers: { "content-type": "image/png" }, + body: route.request().method() === "HEAD" ? "" : png, + }); + if (path.startsWith("/api/")) + return route.fulfill({ status: 404, json: { detail: "Not found." } }); + return route.fulfill({ + contentType: "text/html", + body: `${options.css ? `` : ""}
`, + }); + }); + await page.goto(`${ORIGIN}/${options.only ? `?only=${options.only}` : ""}`); + await page + .locator('figure[aria-label="Making the image"]') + .waitFor({ timeout: 15_000 }); + if (!options.css) await style(page); + return page; +} + +const LOGO = `figure[aria-label="Picture from the Bot: ${PICTURES.logo.name}"]`; +const BANNER = `figure[aria-label="Picture from the Bot: ${PICTURES.banner.name}"]`; +const SENT = `figure[aria-label="File from the Bot: ${PICTURES.chart.name}"]`; +const MAKING = 'figure[aria-label="Making the image"]'; +const VERIFY = '[role="note"][aria-label="The image model needs verification"]'; +const REFUSED = '[role="note"][aria-label="The image model turned this down"]'; +const FAILED = '[role="note"][aria-label="Couldn\'t make the image"]'; +const LIMIT = '[role="note"][aria-label="Image limit reached"]'; + +describe.skipIf(!asked)("a picture a Bot made, in the conversation", () => { + for (const engine of engines) + for (const theme of THEMES) + for (const width of WIDTHS) + test(`every state reads as the app's own card and fits the column, in ${engine}, ${theme}, at ${width}px`, async () => { + const page = await open(engine, theme, width); + try { + // Both pictures loaded, at their own shape. + for (const card of [LOGO, BANNER]) { + const img = page.locator(`${card} img`); + await img.waitFor(); + await page.waitForFunction( + (selector) => { + const element = document.querySelector( + selector, + ) as HTMLImageElement | null; + return ( + element?.complete === true && + element.naturalWidth > 0 && + getComputedStyle(element).opacity === "1" + ); + }, + `${card} img`, + { timeout: 10_000 }, + ); + } + await still(page); + if (shots) { + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join( + shots, + `conversation-${engine}-${theme}-${width}.png`, + ), + fullPage: true, + }); + for (const [name, selector] of [ + ["sent-file", SENT], + ["made-first", LOGO], + ["made-landscape", BANNER], + ["needs-verification", VERIFY], + ["refused", REFUSED], + ["failed", FAILED], + ["limit-reached", LIMIT], + ["making", MAKING], + ] as const) { + const card = page.locator(selector); + await card.scrollIntoViewIfNeeded(); + await card.screenshot({ + path: join(shots, `${name}-${engine}-${theme}-${width}.png`), + }); + } + } + + const box = (selector: string) => + page.locator(selector).evaluate((element) => { + const style = getComputedStyle(element); + const rect = element.getBoundingClientRect(); + return { + left: rect.left, + right: rect.right, + width: rect.width, + height: rect.height, + radius: style.borderTopLeftRadius, + border: style.borderTopColor, + fill: style.backgroundColor, + }; + }); + const sent = await box(SENT); + const logo = await box(LOGO); + const banner = await box(BANNER); + const making = await box(MAKING); + // The sent file's card, to the corner, the border and the fill. + for (const card of [logo, banner, making]) { + expect(card.radius).toBe(sent.radius); + expect(card.border).toBe(sent.border); + expect(card.fill).toBe(sent.fill); + } + expect(await page.locator(LIMIT).textContent()).toContain( + "It resets tomorrow at", + ); + for (const selector of [VERIFY, REFUSED, FAILED, LIMIT]) { + const note = await box(selector); + expect(note.radius).toBe(sent.radius); + expect(note.fill).toBe(sent.fill); + expect(note.right).toBeLessThanOrEqual(width); + } + // As wide as a sent file's card, never wider than the window. + expect(Math.round(logo.width)).toBe(Math.round(sent.width)); + expect(logo.right).toBeLessThanOrEqual(width); + // The portrait being made is narrower, so it never stands taller than the column allows. + expect(making.width).toBeLessThan(logo.width + 0.5); + const placeholder = await page + .locator(`${MAKING} [style*="aspect-ratio"]`) + .evaluate((element) => element.getBoundingClientRect()); + expect(placeholder.height / placeholder.width).toBeCloseTo(1.5, 1); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + + // The first picture names the others, once; the second doesn't. + expect(await page.locator(LOGO).textContent()).toContain( + "You can also ask for Nano Banana 2 or Grok Imagine by name.", + ); + expect(await page.locator(BANNER).textContent()).not.toContain( + "You can also ask for", + ); + expect(await page.locator(LOGO).textContent()).toContain( + "GPT Image 2 · 1024 × 1024", + ); + + // Download saves the stored picture under its name. + const download = page.locator( + `${LOGO} a[aria-label="Download ${PICTURES.logo.name}"]`, + ); + expect(await download.getAttribute("download")).toBe( + PICTURES.logo.name, + ); + expect(await download.getAttribute("href")).toMatch( + new RegExp(`/attachments/${PICTURES.logo.id}$`), + ); + expect(await page.locator(`${VERIFY} a`).getAttribute("href")).toBe( + "https://platform.openai.com/settings/organization/general", + ); + + // A click opens it full screen, in the lightbox the person's own pictures use. + await page + .locator( + `${LOGO} button[aria-label="Open ${PICTURES.logo.name}"]`, + ) + .click(); + const dialog = page.getByRole("dialog"); + await dialog.waitFor(); + // The lightbox's own classes arrive with it. + await style(page); + const full = dialog.locator("img"); + await full.waitFor(); + await page.waitForFunction(() => { + const element = document.querySelector( + '[role="dialog"] img', + ) as HTMLImageElement | null; + return element?.complete && element.naturalWidth > 0; + }); + await still(page); + if (shots) + await page.screenshot({ + path: join(shots, `lightbox-${engine}-${theme}-${width}.png`), + }); + const fullBox = await full.boundingBox(); + expect(fullBox?.width ?? 0).toBeGreaterThan(logo.width * 0.9); + await page.keyboard.press("Escape"); + await dialog.waitFor({ state: "detached" }); + } finally { + await page.close(); + } + }, 120_000); + + for (const engine of engines) + for (const theme of THEMES) + test(`a picture being made paints in, frame first, in ${engine}, ${theme}`, async () => { + // The page's own classes, read once drawn still, and every class the card can take. + const first = await open(engine, theme, 390, { only: "making" }); + const css = await stylesheet([ + ...(await classesOn(first)), + ...cardClasses(), + ]); + await first.close(); + const page = await open(engine, theme, 390, { + only: "making", + motion: "no-preference", + css, + }); + try { + const card = page.locator(MAKING); + // Each frame's look, from the first: the frame dashed, then filled, then drawn. + const looks: string[] = []; + for (let frame = 0; frame < 6; frame += 1) { + const look = await card.evaluate( + (element) => + `${getComputedStyle(element).borderTopStyle} ${element.querySelector(".image-painting") ? "painting" : "placeholder"}`, + ); + looks.push(look); + if (shots) { + mkdirSync(shots, { recursive: true }); + await card.screenshot({ + path: join( + shots, + `making-paint-${frame}-${engine}-${theme}.png`, + ), + animations: "allow", + }); + } + await page.waitForTimeout(120); + } + // Drawn as an outline first, and as the card with the light moving across it in the end. + expect( + await page.evaluate( + () => (window as { firstLook?: string }).firstLook, + ), + ).toBe("dashed placeholder"); + expect(looks.at(-1)).toBe("solid painting"); + if (shots) + await card.screenshot({ + path: join(shots, `making-painted-${engine}-${theme}.png`), + }); + expect(await card.textContent()).toContain("Making the image"); + expect(await card.textContent()).toContain( + "A tall poster for the offsite's evening", + ); + expect(await card.getAttribute("aria-busy")).toBe("true"); + } finally { + await page.close(); + } + }, 60_000); +}); diff --git a/app/tests/generated-image-card.test.tsx b/app/tests/generated-image-card.test.tsx new file mode 100644 index 0000000000..7af2005e75 --- /dev/null +++ b/app/tests/generated-image-card.test.tsx @@ -0,0 +1,400 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { GENERATE_IMAGE_TOOL } from "@openbot/shared/generate-image"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, within } from "@testing-library/react"; +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { resetsWhen } from "@/components/channels/generated-image-card"; +import { attachmentAddress } from "@/lib/channels/attachments"; +import { GenerateImageTool } from "@/lib/copilot/generate-image-tool"; +import { readableTurns } from "@/lib/copilot/thread-messages"; +import { settleReactWork } from "./settle-react-work"; + +/** + * A picture a Bot made, as the conversation draws it: while it is being made, once it is made, and + * when it wasn't, live and after a reload. + * + * Every conversation here is read the way a reopened one is: turns in the history store's own + * dialect (`{id, name, args}`, the arguments as an object), through `readableTurns`, into the app's + * transcript with the renderer the app registers for `generate_image`. The answers are in the + * contract's shape exactly (shared/generate-image.ts), as the server stores them. The server is + * faked at the HTTP boundary only, answering an attachment's address as the real one does. + */ + +const PICTURE = "5b0e6f1c-1a2b-4c3d-8e9f-0a1b2c3d4e5f"; +const NAME = "retro-teal-offsite-logo.png"; +const PROMPT = + "A retro logo for our team offsite: teal and cream, a sun over hills, the words OFFSITE 2026"; + +const server = setupServer( + http.head( + "*/api/v2/organizations/:organizationId/attachments/:id", + () => new HttpResponse(null, { status: 200 }), + ), + http.all("*", () => new HttpResponse(null, { status: 404 })), +); + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); + server.listen({ onUnhandledRequest: "bypass" }); +}); +afterEach(() => { + cleanup(); + server.resetHandlers(); +}); +afterAll(async () => { + server.close(); + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +const made = (extra: object = {}) => ({ + ok: true, + image: { + attachmentId: PICTURE, + name: NAME, + mimeType: "image/png", + sizeBytes: 1_482_113, + url: `/api/attachments/${PICTURE}`, + width: 1024, + height: 1024, + }, + model: { id: "gpt-image-2", label: "GPT Image 2", vendor: "openai" }, + prompt: PROMPT, + ...extra, +}); + +/** A conversation in which the person asked for a picture and the Bot called `generate_image`. */ +function storedThread( + args: Record, + answer: unknown | undefined, + after?: string, +) { + return [ + { + id: "u1", + role: "user", + content: "Make a logo for our offsite, retro, teal", + }, + { + id: "a1", + role: "assistant", + content: null, + toolCalls: [{ id: "call_image", name: GENERATE_IMAGE_TOOL, args }], + }, + ...(answer === undefined + ? [] + : [ + { + id: "r1", + role: "tool", + toolCallId: "call_image", + content: + typeof answer === "string" ? answer : JSON.stringify(answer), + }, + ]), + ...(after ? [{ id: "a2", role: "assistant", content: after }] : []), + ]; +} + +function draw(stored: unknown[], busy = false) { + const { messages, unreadable } = readableTurns(stored); + expect(unreadable).toBe(0); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const rootRoute = createRootRoute({ + component: () => ( + + + + + ), + }); + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + return render( + + + , + ); +} + +const ADDRESS = () => attachmentAddress(`/api/attachments/${PICTURE}`); + +test("while the picture is being made, the card is there at its shape, with the prompt", async () => { + const view = draw( + storedThread({ prompt: PROMPT, aspect: "portrait" }, undefined), + true, + ); + const card = await view.findByRole("figure", { name: "Making the image" }); + expect(card.getAttribute("aria-busy")).toBe("true"); + expect(within(card).getByRole("status").textContent).toBe("Making the image"); + expect(within(card).getByText(PROMPT)).toBeTruthy(); + // Portrait: two wide by three high, and narrowed so it never stands taller than 28rem. + const box = card.querySelector('[style*="aspect-ratio"]') as HTMLElement; + expect(box.style.aspectRatio).toBe("2 / 3"); + expect(card.style.maxWidth).toBe("min(24rem, 18.667rem)"); + // Nothing to download yet, and no picture. + expect(within(card).queryByRole("button", { name: /Download/ })).toBeNull(); + expect(card.querySelector("img")).toBeNull(); +}); + +test("a made picture shows itself, opens full size, names its model and downloads under its name, now and on reload", async () => { + // A reload draws from the stored thread, which is this same list: drawn twice, from scratch. + for (let pass = 0; pass < 2; pass += 1) { + const view = draw( + storedThread({ prompt: PROMPT }, made(), "Here's your offsite logo."), + ); + const card = within( + await view.findByRole("figure", { + name: `Picture from the Bot: ${NAME}`, + }), + ); + const picture = card.getByRole("img", { name: PROMPT }); + expect(picture.getAttribute("src")).toBe(ADDRESS()); + // The same lightbox the person's own pictures open in. + expect(card.getByRole("button", { name: `Open ${NAME}` })).toBeTruthy(); + const caption = card.getByText("GPT Image 2 · 1024 × 1024"); + expect(caption.getAttribute("title")).toBe("Made with GPT Image 2"); + const download = card.getByRole("button", { name: `Download ${NAME}` }); + expect(download.getAttribute("href")).toBe(ADDRESS()); + expect(download.getAttribute("download")).toBe(NAME); + // Not a first picture with others to name, so no line about them. + expect(card.queryByText(/You can also ask for/)).toBeNull(); + // Never folded behind a line: the picture is for the person. + expect( + view.container + .querySelector(`figure[aria-label="Picture from the Bot: ${NAME}"]`) + ?.closest("details"), + ).toBeNull(); + cleanup(); + } +}); + +test("on a person's first picture, the other models they could ask for are named once, quietly", async () => { + const view = draw( + storedThread( + { prompt: PROMPT }, + made({ + otherModels: [ + { id: "gemini-3.1-flash-image", label: "Nano Banana 2" }, + { id: "grok-imagine", label: "Grok Imagine" }, + ], + }), + ), + ); + const card = within( + await view.findByRole("figure", { name: `Picture from the Bot: ${NAME}` }), + ); + expect( + card.getByText( + "You can also ask for Nano Banana 2 or Grok Imagine by name.", + ), + ).toBeTruthy(); +}); + +test("a picture with no size in its answer says its file size instead", async () => { + const answer = made(); + const { width: _w, height: _h, ...image } = answer.image; + const view = draw( + storedThread({ prompt: PROMPT, aspect: "landscape" }, { ...answer, image }), + ); + const card = await view.findByRole("figure", { + name: `Picture from the Bot: ${NAME}`, + }); + expect(within(card).getByText("GPT Image 2 · 1.4 MB")).toBeTruthy(); + // The shape the Bot asked for holds the place. + const box = card.querySelector('[style*="aspect-ratio"]') as HTMLElement; + expect(box.style.aspectRatio).toBe("3 / 2"); +}); + +test("a provider that wants the organization verified says so, with the page to do it on", async () => { + const message = + "OpenAI needs your organization verified before it makes pictures. Verify it on OpenAI's site, then ask again."; + const view = draw( + storedThread( + { prompt: PROMPT }, + { + ok: false, + reason: "needs_verification", + message, + fixUrl: "https://platform.openai.com/settings/organization/general", + }, + ), + ); + const note = within( + await view.findByRole("note", { + name: "The image model needs verification", + }), + ); + expect(note.getByText(message)).toBeTruthy(); + const fix = note.getByRole("button", { name: /Verify your organization/ }); + expect(fix.getAttribute("href")).toBe( + "https://platform.openai.com/settings/organization/general", + ); + expect(fix.getAttribute("target")).toBe("_blank"); + expect(note.getByText(`Asked for: ${PROMPT}`)).toBeTruthy(); +}); + +test("a used-up image limit says when it resets, in the person's own time, with the plan's page", async () => { + const now = new Date(); + const nine = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate() + 1, + 9, + 0, + ); + const clock = new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + }).format(nine); + const message = + "Your ChatGPT plan has made as many pictures as it allows for now."; + const view = draw( + storedThread( + { prompt: PROMPT }, + { + ok: false, + reason: "limit_reached", + message, + resetsAt: nine.toISOString(), + fixUrl: "https://chatgpt.com/#pricing", + }, + ), + ); + const note = within( + await view.findByRole("note", { name: "Image limit reached" }), + ); + expect(note.getByText(message)).toBeTruthy(); + expect(note.getByText(`It resets tomorrow at ${clock}.`)).toBeTruthy(); + expect( + note + .getByRole("button", { name: /Upgrade your plan/ }) + .getAttribute("href"), + ).toBe("https://chatgpt.com/#pricing"); + cleanup(); + + // Nobody said when: no time is made up. + const unsaid = draw( + storedThread( + { prompt: PROMPT }, + { ok: false, reason: "limit_reached", message }, + ), + ); + const plain = await unsaid.findByRole("note", { + name: "Image limit reached", + }); + expect(plain.textContent).not.toContain("It resets"); +}); + +test("when a limit resets reads as today, tomorrow or the day, and never as a time already past", () => { + const now = new Date(2026, 10, 30, 14, 0); + const at = (days: number, hour: number) => + new Date(2026, 10, 30 + days, hour, 30).toISOString(); + const clock = (iso: string) => + new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + }).format(new Date(iso)); + expect(resetsWhen(at(0, 16), now)).toBe(`today at ${clock(at(0, 16))}`); + expect(resetsWhen(at(1, 1), now)).toBe(`tomorrow at ${clock(at(1, 1))}`); + const later = new Intl.DateTimeFormat(undefined, { + weekday: "long", + month: "long", + day: "numeric", + }).format(new Date(at(3, 9))); + expect(resetsWhen(at(3, 9), now)).toBe(`on ${later} at ${clock(at(3, 9))}`); + expect(resetsWhen(at(0, 9), now)).toBeNull(); + expect(resetsWhen("not a time", now)).toBeNull(); +}); + +for (const [reason, heading, message] of [ + [ + "refused", + "The image model turned this down", + "The image model said this prompt goes against its rules. Try describing it differently.", + ], + [ + "no_image_model", + "No image model to use", + "None of your organization's AI connections can make pictures. An admin can add one that can, such as OpenAI or Google.", + ], + [ + "unknown_model", + "That image model isn't available", + "Midjourney isn't one of the image models your organization can use. You can use GPT Image 2 or Nano Banana 2.", + ], + [ + "too_large", + "The image was too large to keep", + "The picture came back larger than OpenBot keeps. Ask for it again, smaller.", + ], + [ + "failed", + "Couldn't make the image", + "OpenAI didn't answer in time. Try again in a moment.", + ], +] as const) + test(`a picture not made (${reason}) says why in plain words, and offers no link it wasn't given`, async () => { + const view = draw( + storedThread({ prompt: PROMPT }, { ok: false, reason, message }), + ); + const note = within(await view.findByRole("note", { name: heading })); + expect(note.getByText(message)).toBeTruthy(); + expect(note.queryByRole("button")).toBeNull(); + expect(view.queryByRole("figure")).toBeNull(); + }); + +test("a call its run ended under, with no answer of its own, says so instead of making forever", async () => { + // No answer, turn over: the page closed, or the person stopped it. + const stopped = draw(storedThread({ prompt: PROMPT }, undefined)); + expect( + await stopped.findByRole("note", { + name: "Stopped before the image was ready", + }), + ).toBeTruthy(); + expect( + stopped.queryByRole("figure", { name: "Making the image" }), + ).toBeNull(); + cleanup(); + + // The runtime's own answer for a step its run ended under, in its own words. + const closed = draw( + storedThread( + { prompt: PROMPT }, + { + status: "stopped", + reason: "run_stopped", + message: "The run was stopped before this step finished.", + }, + ), + ); + const note = within( + await closed.findByRole("note", { name: "Couldn't make the image" }), + ); + expect( + note.getByText("The run was stopped before this step finished."), + ).toBeTruthy(); +}); + +test("the picture's name in the Bot's words downloads the picture", async () => { + const view = draw( + storedThread({ prompt: PROMPT }, made(), `Here it is: [${NAME}](${NAME}).`), + ); + const link = await view.findByRole("link", { name: NAME }); + expect(link.getAttribute("href")).toBe(ADDRESS()); + expect(link.hasAttribute("download")).toBe(true); +}); diff --git a/app/tests/no-fixed-settle-waits.test.ts b/app/tests/no-fixed-settle-waits.test.ts index c173cd0591..33655b4d80 100644 --- a/app/tests/no-fixed-settle-waits.test.ts +++ b/app/tests/no-fixed-settle-waits.test.ts @@ -55,6 +55,10 @@ const ALLOWED: Record = { most: 2, why: "photographs what a first message shows a set time after Send, and after a run starts with nothing said yet", }, + "generated-image-browser.test.tsx": { + most: 1, + why: "photographs a picture card's paint-in at set times as it goes from outline to drawn", + }, "moved-apps-reconnect.test.tsx": { most: 9, why: "proves nothing is said or asked after a move; its one settle wait, after styling, is still to move to still()", From c114bbb24a8a57781ef2e47420f3e65e2b4ed256 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 14:50:04 -0800 Subject: [PATCH 007/224] API: remove a Bot's key, and name the Bots a move couldn't bring a key for (#2534) Adds removeBotKey (POST .../bots/{botId}/remove-key), so an existing Bot's key can be set, replaced (updateBot's auth) and removed. Documents the BOT_KEY_REFUSED code a run ends with when a Bot's address refuses it with 401 or 403. Adds the move note bot-key-not-brought, with the Bots it is about by id, for a Bot whose key couldn't come across in a move. --- api/openapi.yaml | 70 +++++- api/openapi/bots.yaml | 57 ++++- api/openapi/common.yaml | 1 + api/openapi/moves.yaml | 23 +- app/src/lib/api/generated/bots/bots.msw.ts | 59 +++++ app/src/lib/api/generated/bots/bots.ts | 143 ++++++++++++ app/src/lib/api/generated/bots/bots.zod.ts | 221 +++++++++++++++++- app/src/lib/api/generated/model/bot.ts | 2 +- app/src/lib/api/generated/model/index.ts | 2 + app/src/lib/api/generated/model/moveNote.ts | 5 +- .../lib/api/generated/model/moveNoteBot.ts | 10 + .../generated/model/removeBotKeyHeaders.ts | 13 ++ .../moving-to-openbot-cloud.zod.ts | 102 +++++++- mobile/src/api/generated/bots/bots.ts | 19 ++ mobile/src/api/generated/model/bot.ts | 2 +- 15 files changed, 706 insertions(+), 23 deletions(-) create mode 100644 app/src/lib/api/generated/model/moveNoteBot.ts create mode 100644 app/src/lib/api/generated/model/removeBotKeyHeaders.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index 13ca377233..7b1eb57096 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -17141,6 +17141,54 @@ paths: $ref: '#/components/responses/ServerError' default: $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/bots/{botId}/remove-key: + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/BotId' + post: + tags: + - Bots + operationId: removeBotKey + summary: Remove a Bot's key + description: Stop sending a key to the address a Bot runs at, and retire the key so it can't be read or used again. Its runs then reach the address with no key. Setting or replacing a key is updateBot's auth. Only whoever may manage the Bot may remove it. Removing a key that is not there changes nothing. + security: + - webSession: [] + - appOAuth: + - bots:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + responses: + '200': + description: The Bot, with no key. + headers: + Cache-Control: + $ref: '#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/BotResponse' + examples: + removed: + $ref: '#/components/examples/CreatedBot' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/BotForbidden' + '404': + $ref: '#/components/responses/BotNotFound' + '409': + $ref: '#/components/responses/IdempotencyConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + default: + $ref: '#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/bots/{botId}/report-decline: parameters: - $ref: '#/components/parameters/OrganizationId' @@ -26570,7 +26618,7 @@ components: description: The AG-UI address it runs at, as it was stored. Null for a Bot that runs inside OpenBot. Every address saved through this API is an absolute http or https address (see the request's endpoint), but one saved by an older release is returned as it is, so this field states no format. hasAuth: type: boolean - description: Whether a key is set for its address. Never the key. + description: Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key. hasCallbackToken: type: boolean description: Whether it holds a credential for calling OpenBot's tools back. Never the credential. @@ -44298,6 +44346,18 @@ components: type: string minLength: 1 description: What went wrong, when failed, in a sentence a person reads. + MoveNoteBot: + type: object + required: + - id + - name + properties: + id: + type: string + description: The Bot's id in the organization the move went into. + name: + type: string + description: The Bot's name. MoveNote: type: object description: Something that moved differently, or not at all, and why, in a sentence a person reads. @@ -44313,7 +44373,8 @@ components: - model-key-kept-existing - model-key-not-brought - item-skipped - description: 'isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn''t on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn''t be imported; message says which and why. A later OpenBot may add a code; show the message.' + - bot-key-not-brought + description: 'isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn''t on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn''t be imported; message says which and why. bot-key-not-brought: the key a Bot''s address sits behind couldn''t come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.' kind: $ref: '#/components/schemas/MoveKind' count: @@ -44328,6 +44389,11 @@ components: description: The names of the items, such as the Bots, when there are a few. items: type: string + bots: + type: array + description: The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise. + items: + $ref: '#/components/schemas/MoveNoteBot' Import: type: object required: diff --git a/api/openapi/bots.yaml b/api/openapi/bots.yaml index 3ff2d4d83e..aec24ffad4 100644 --- a/api/openapi/bots.yaml +++ b/api/openapi/bots.yaml @@ -713,6 +713,57 @@ paths: $ref: './common.yaml#/components/responses/ServerError' default: $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/bots/{botId}/remove-key: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/BotId' + post: + tags: [Bots] + operationId: removeBotKey + summary: Remove a Bot's key + description: >- + Stop sending a key to the address a Bot runs at, and retire the key so + it can't be read or used again. Its runs then reach the address with no + key. Setting or replacing a key is updateBot's auth. Only whoever may + manage the Bot may remove it. Removing a key that is not there changes + nothing. + security: + - webSession: [] + - appOAuth: [bots:write] + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + responses: + '200': + description: The Bot, with no key. + headers: + Cache-Control: + $ref: './common.yaml#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/BotResponse' + examples: + removed: + $ref: '#/components/examples/CreatedBot' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/BotForbidden' + '404': + $ref: '#/components/responses/BotNotFound' + '409': + $ref: './common.yaml#/components/responses/IdempotencyConflict' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/bots/{botId}/report-decline: parameters: - $ref: './common.yaml#/components/parameters/OrganizationId' @@ -1675,7 +1726,11 @@ components: states no format. hasAuth: type: boolean - description: Whether a key is set for its address. Never the key. + description: >- + Whether a key is set for its address. Never the key. Set or replace + it with updateBot's auth, and remove it with removeBotKey. A run + its address refuses with 401 or 403 ends in a RUN_ERROR whose code + is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key. hasCallbackToken: type: boolean description: >- diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 1fc5c09ec8..14f1d33d15 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -439,6 +439,7 @@ paths: /api/v2/organizations/{organizationId}/bots/{botId}/unpin: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1unpin' } /api/v2/organizations/{organizationId}/bots/{botId}/issue-callback-token: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1issue-callback-token' } /api/v2/organizations/{organizationId}/bots/{botId}/revoke-callback-token: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1revoke-callback-token' } + /api/v2/organizations/{organizationId}/bots/{botId}/remove-key: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1remove-key' } /api/v2/organizations/{organizationId}/bots/{botId}/report-decline: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1report-decline' } /api/v2/organizations/{organizationId}/bots/{botId}/handoff: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1handoff' } /api/v2/organizations/{organizationId}/bots/{botId}/lifecycle: { $ref: './bots.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bots~1{botId}~1lifecycle' } diff --git a/api/openapi/moves.yaml b/api/openapi/moves.yaml index 0740d0e65f..f55bffddca 100644 --- a/api/openapi/moves.yaml +++ b/api/openapi/moves.yaml @@ -807,6 +807,7 @@ components: - model-key-kept-existing - model-key-not-brought - item-skipped + - bot-key-not-brought description: >- isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. @@ -815,7 +816,9 @@ components: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which - and why. A later OpenBot may add a code; show the message. + and why. bot-key-not-brought: the key a Bot's address sits behind + couldn't come across, so the Bot needs it set again here; bots + names each one. A later OpenBot may add a code; show the message. kind: $ref: '#/components/schemas/MoveKind' count: @@ -830,6 +833,24 @@ components: description: The names of the items, such as the Bots, when there are a few. items: type: string + bots: + type: array + description: >- + The Bots the note is about, by their id here, so a client can open + each one. Only on a note about Bots that need something done + (bot-key-not-brought); absent otherwise. + items: + $ref: '#/components/schemas/MoveNoteBot' + MoveNoteBot: + type: object + required: [id, name] + properties: + id: + type: string + description: The Bot's id in the organization the move went into. + name: + type: string + description: The Bot's name. ExportEstimate: type: object required: [counts, estimatedBytes, storedBytes, reconnect, modelKeysAvailable] diff --git a/app/src/lib/api/generated/bots/bots.msw.ts b/app/src/lib/api/generated/bots/bots.msw.ts index 4a413271ea..f859092a8a 100644 --- a/app/src/lib/api/generated/bots/bots.msw.ts +++ b/app/src/lib/api/generated/bots/bots.msw.ts @@ -323,6 +323,34 @@ export const getRevokeBotCallbackTokenResponseMock = (): BotResponse => ({ }, }); +export const getRemoveBotKeyResponseMock = (): BotResponse => ({ + bot: { + id: "agent_9b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", + name: "Expense Review", + title: "Finance Operations", + roleDescription: + "Review receipts, categorize expenses, and prepare reimbursement reports.", + avatarSeed: "agent_9b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", + visibility: "private", + hidden: false, + pinned: false, + systemOwned: false, + endpoint: null, + hasAuth: false, + hasCallbackToken: false, + isolated: false, + framework: "OpenBot", + canManage: true, + mine: true, + assignedToMe: false, + builtIn: false, + runsOnOpenBotModel: true, + keyFromOpenBot: false, + isolationActive: false, + isolationOffReason: null, + }, +}); + export const getGetBotHandoffResponseMock = (): BotHandoff => ({ enabled: true, canGrant: false, @@ -821,6 +849,36 @@ export const getRevokeBotCallbackTokenMockHandler = ( ); }; +export const getRemoveBotKeyMockHandler = ( + overrideResponse?: + | BotResponse + | (( + info: Parameters< + HttpResponseResolver<{ organizationId: string; botId: string }> + >[0], + ) => Promise | BotResponse), + options?: RequestHandlerOptions, +) => { + return http.post<{ organizationId: string; botId: string }>( + "*/api/v2/organizations/:organizationId/bots/:botId/remove-key", + async ( + info: Parameters< + HttpResponseResolver<{ organizationId: string; botId: string }> + >[0], + ) => { + return HttpResponse.json( + overrideResponse !== undefined + ? typeof overrideResponse === "function" + ? await overrideResponse(info) + : overrideResponse + : getRemoveBotKeyResponseMock(), + { status: 200 }, + ); + }, + options, + ); +}; + export const getReportBotDeclineMockHandler = ( overrideResponse?: | void @@ -1119,6 +1177,7 @@ export const getBotsMock = () => [ getUnpinBotMockHandler(), getIssueBotCallbackTokenMockHandler(), getRevokeBotCallbackTokenMockHandler(), + getRemoveBotKeyMockHandler(), getReportBotDeclineMockHandler(), getGetBotHandoffMockHandler(), getGetBotLifecycleMockHandler(), diff --git a/app/src/lib/api/generated/bots/bots.ts b/app/src/lib/api/generated/bots/bots.ts index 2581ba8b44..dcd0906f0d 100644 --- a/app/src/lib/api/generated/bots/bots.ts +++ b/app/src/lib/api/generated/bots/bots.ts @@ -51,6 +51,7 @@ import type { OwnOnlyResponse, PauseBotHeaders, PinBotHeaders, + RemoveBotKeyHeaders, ReportBotDeclineHeaders, ResetBotHeaders, ResumeBotHeaders, @@ -2123,6 +2124,148 @@ export const useRevokeBotCallbackToken = < queryClient, ); }; +export const getRemoveBotKeyUrl = (organizationId: string, botId: string) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/bots/${encodeURIComponent(String(botId))}/remove-key`; +}; + +/** + * Stop sending a key to the address a Bot runs at, and retire the key so it can't be read or used again. Its runs then reach the address with no key. Setting or replacing a key is updateBot's auth. Only whoever may manage the Bot may remove it. Removing a key that is not there changes nothing. + * @summary Remove a Bot's key + */ +export const removeBotKey = async ( + organizationId: string, + botId: string, + headers: RemoveBotKeyHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest(getRemoveBotKeyUrl(organizationId, botId), { + ...options, + method: "POST", + headers: { ...headers, ...getHeaders(options?.headers) }, + }); +}; + +export const getRemoveBotKeyMutationKey = () => ["removeBotKey"] as const; + +export const getRemoveBotKeyMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | BotForbiddenResponse + | BotNotFoundResponse + | IdempotencyConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RemoveBotKeyMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + RemoveBotKeyMutationVariables, + TContext +> => { + const mutationKey = getRemoveBotKeyMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + RemoveBotKeyMutationVariables + > = (props) => { + const { organizationId, botId, headers } = props ?? {}; + + return removeBotKey(organizationId, botId, headers, requestOptions); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type RemoveBotKeyMutationResult = NonNullable< + Awaited> +>; + +export type RemoveBotKeyMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | BotForbiddenResponse + | BotNotFoundResponse + | IdempotencyConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse; +export type RemoveBotKeyMutationVariables = { + organizationId: string; + botId: string; + headers: RemoveBotKeyHeaders; +}; + +/** + * @summary Remove a Bot's key + */ +export const useRemoveBotKey = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | BotForbiddenResponse + | BotNotFoundResponse + | IdempotencyConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RemoveBotKeyMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + RemoveBotKeyMutationVariables, + TContext +> => { + return useMutation(getRemoveBotKeyMutationOptions(options), queryClient); +}; export const getReportBotDeclineUrl = ( organizationId: string, botId: string, diff --git a/app/src/lib/api/generated/bots/bots.zod.ts b/app/src/lib/api/generated/bots/bots.zod.ts index c30111c577..7d165528a8 100644 --- a/app/src/lib/api/generated/bots/bots.zod.ts +++ b/app/src/lib/api/generated/bots/bots.zod.ts @@ -109,7 +109,9 @@ export const ListBotsResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -395,7 +397,9 @@ export const CreateBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -562,7 +566,9 @@ export const GetBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -864,7 +870,9 @@ export const UpdateBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -1173,7 +1181,9 @@ export const DuplicateBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -1352,7 +1362,9 @@ export const HideBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -1531,7 +1543,9 @@ export const UnhideBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -1710,7 +1724,9 @@ export const PinBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -1889,7 +1905,9 @@ export const UnpinBotResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( @@ -2110,7 +2128,190 @@ export const RevokeBotCallbackTokenResponse = zod.object({ ), hasAuth: zod .boolean() - .describe("Whether a key is set for its address. Never the key."), + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), + hasCallbackToken: zod + .boolean() + .describe( + "Whether it holds a credential for calling OpenBot's tools back. Never the credential.", + ), + isolated: zod + .boolean() + .describe( + "Whether its owner asked for it to have a computer of its own. isolationActive says whether it has one now.", + ), + computer: zod + .string() + .optional() + .describe( + "The computer it works on: browser, the Bot's own browser computer, which every Bot has unless told otherwise; or windows, the Windows computer of the person it works for: in a conversation, theirs; in a routine, its owner's. One at a time. Experimental.", + ), + instructions: zod + .string() + .optional() + .describe( + "What the starter Bot is told, kept apart from its role description. Only the starter Bot has instructions.", + ), + framework: zod + .string() + .optional() + .describe( + 'What runs it, by the name a person reads ("LangChain", "OpenBot"). Absent when OpenBot doesn\'t know.', + ), + canManage: zod + .boolean() + .describe("Whether the caller may change and delete it."), + mine: zod + .boolean() + .describe( + "Whether the caller created it. Separate from canManage, which is also true for an administrator on everybody's Bots.", + ), + withheld: zod + .boolean() + .optional() + .describe( + "Whether it is somebody else's private Bot, listed for an admin's screens (listBots with scope=organization) and nothing more. Such a Bot carries its id, name, avatar and the caller's own state with it only: title and roleDescription are empty, endpoint is null, instructions and framework are absent, hasAuth, hasCallbackToken, isolated, builtIn, runsOnOpenBotModel, keyFromOpenBot and canManage are false. Absent or false on every other Bot.", + ), + assignedToMe: zod + .boolean() + .describe("Whether an administrator assigned this Bot to the caller."), + lastConversationAt: zod.iso + .datetime({ offset: true }) + .nullish() + .describe( + "When a conversation of the caller's with this Bot last had a message, the Bot's or anybody's, or was started if it has none yet; null when the caller has none. Counts the conversations listConversations lists. Set on listBots.", + ), + builtIn: zod + .boolean() + .describe( + "Whether it runs at the deployment's own managed address, so it needs no callback credential of its own.", + ), + runsOnOpenBotModel: zod + .boolean() + .describe( + "Whether it runs on OpenBot's model, so a person can pick the model per conversation.", + ), + defaultModel: zod + .object({ + model: zod.string(), + effort: zod.string().nullable(), + source: zod + .string() + .describe( + "The model connection source when the default was saved.", + ), + }) + .nullish() + .describe( + "The Bot's saved default model and thinking level. Null follows the deployment default.", + ), + keyFromOpenBot: zod + .boolean() + .describe( + "Whether OpenBot gives it a key for its tools on every run, because OpenBot runs it.", + ), + isolationActive: zod + .boolean() + .describe("Whether its next run gets a computer of its own."), + isolationOffReason: zod + .union([ + zod.literal("admin"), + zod.literal("deployment"), + zod.literal(null), + ]) + .nullable() + .describe( + "Why an isolated Bot runs on a shared computer instead. admin: its owner no longer holds Isolated Bots. deployment: this deployment cannot make another computer. Null otherwise.", + ), + }) + .describe( + "A Bot as the caller sees it. canManage, mine, systemOwned and the isolation fields are the server's verdicts for this caller; a client renders them and never recomputes them. No secret is ever part of a Bot: hasAuth and hasCallbackToken say whether one is set.", + ), +}); + +/** + * Stop sending a key to the address a Bot runs at, and retire the key so it can't be read or used again. Its runs then reach the address with no key. Setting or replacing a key is updateBot's auth. Only whoever may manage the Bot may remove it. Removing a key that is not there changes nothing. + * @summary Remove a Bot's key + */ + +export const removeBotKeyPathBotIdRegExp = new RegExp("\\S"); + +export const RemoveBotKeyParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), + botId: zod + .string() + .min(1) + .regex(removeBotKeyPathBotIdRegExp) + .describe("The Bot's id."), +}); + +export const removeBotKeyHeaderIdempotencyKeyMax = 128; + +export const RemoveBotKeyHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(removeBotKeyHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const RemoveBotKeyResponse = zod.object({ + bot: zod + .object({ + id: zod.string().describe("The Bot's id."), + name: zod.string().describe("What the Bot is called."), + title: zod + .string() + .describe("The subtitle under its name. May be empty."), + roleDescription: zod + .string() + .describe("What it does, in its owner's words."), + avatarSeed: zod.string().describe("The seed its avatar is drawn from."), + visibility: zod + .enum(["public", "private"]) + .describe("Public Bots are shared with everybody in the organization."), + hidden: zod + .boolean() + .describe("Whether the caller hid it from their own list."), + pinned: zod + .boolean() + .describe("Whether the caller pinned it to the top of their own list."), + systemOwned: zod + .boolean() + .describe( + "Whether it comes with OpenBot rather than belonging to a person.", + ), + ownerless: zod + .boolean() + .optional() + .describe( + "Whether nobody owns it, as with a Bot OpenBot made for everyone in the organization. Only an admin can give such a Bot apps. Absent or false for a Bot a person owns. Never accepted when a Bot is created or changed.", + ), + packageBotId: zod + .string() + .nullish() + .describe( + "Which of the Bots an OpenBot starts with this one is, so a client recognises it in whichever organization it is in. It is the id that Bot has in the install package: the same as id in the organization `default`, and the package's id on another organization's copy, whose own id is generated. Null for a Bot somebody made. Never accepted when a Bot is created or changed.", + ), + endpoint: zod + .string() + .nullable() + .describe( + "The AG-UI address it runs at, as it was stored. Null for a Bot that runs inside OpenBot. Every address saved through this API is an absolute http or https address (see the request's endpoint), but one saved by an older release is returned as it is, so this field states no format.", + ), + hasAuth: zod + .boolean() + .describe( + "Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key.", + ), hasCallbackToken: zod .boolean() .describe( diff --git a/app/src/lib/api/generated/model/bot.ts b/app/src/lib/api/generated/model/bot.ts index 4f29bb8f04..efbc3cab94 100644 --- a/app/src/lib/api/generated/model/bot.ts +++ b/app/src/lib/api/generated/model/bot.ts @@ -38,7 +38,7 @@ export interface Bot { * @nullable */ endpoint: string | null; - /** Whether a key is set for its address. Never the key. */ + /** Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key. */ hasAuth: boolean; /** Whether it holds a credential for calling OpenBot's tools back. Never the credential. */ hasCallbackToken: boolean; diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index 871c41937e..246610b284 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -1146,6 +1146,7 @@ export * from "./moveCount"; export * from "./moveKind"; export * from "./moveNotAllowedResponse"; export * from "./moveNote"; +export * from "./moveNoteBot"; export * from "./moveRecipientKey"; export * from "./moveUnavailableResponse"; export * from "./narrateInBotBrowserHeaders"; @@ -1342,6 +1343,7 @@ export * from "./rejectPersonLearningProposalParams"; export * from "./releaseComputerControlHeaders"; export * from "./releaseWindowsComputerControlHeaders"; export * from "./removeAiConnectionHeaders"; +export * from "./removeBotKeyHeaders"; export * from "./removeConversationMemberHeaders"; export * from "./removeOrganizationMemberHeaders"; export * from "./removePersonalAiConnectionHeaders"; diff --git a/app/src/lib/api/generated/model/moveNote.ts b/app/src/lib/api/generated/model/moveNote.ts index 84c73bad89..c0d1347611 100644 --- a/app/src/lib/api/generated/model/moveNote.ts +++ b/app/src/lib/api/generated/model/moveNote.ts @@ -2,12 +2,13 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { MoveKind } from "./moveKind"; +import type { MoveNoteBot } from "./moveNoteBot"; /** * Something that moved differently, or not at all, and why, in a sentence a person reads. */ export interface MoveNote { - /** isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message. */ + /** isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message. */ code: string; kind?: MoveKind; /** @@ -19,4 +20,6 @@ export interface MoveNote { message: string; /** The names of the items, such as the Bots, when there are a few. */ items?: string[]; + /** The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise. */ + bots?: MoveNoteBot[]; } diff --git a/app/src/lib/api/generated/model/moveNoteBot.ts b/app/src/lib/api/generated/model/moveNoteBot.ts new file mode 100644 index 0000000000..9f3fb3a2df --- /dev/null +++ b/app/src/lib/api/generated/model/moveNoteBot.ts @@ -0,0 +1,10 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +export interface MoveNoteBot { + /** The Bot's id in the organization the move went into. */ + id: string; + /** The Bot's name. */ + name: string; +} diff --git a/app/src/lib/api/generated/model/removeBotKeyHeaders.ts b/app/src/lib/api/generated/model/removeBotKeyHeaders.ts new file mode 100644 index 0000000000..143549ab2f --- /dev/null +++ b/app/src/lib/api/generated/model/removeBotKeyHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type RemoveBotKeyHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod.ts b/app/src/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod.ts index 18f781c053..f2ce2d8fe0 100644 --- a/app/src/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod.ts +++ b/app/src/lib/api/generated/moving-to-openbot-cloud/moving-to-openbot-cloud.zod.ts @@ -773,7 +773,7 @@ export const CreateImportResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -793,6 +793,21 @@ export const CreateImportResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", @@ -1048,7 +1063,7 @@ export const ListImportsResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -1068,6 +1083,21 @@ export const ListImportsResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", @@ -1297,7 +1327,7 @@ export const GetImportResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -1317,6 +1347,21 @@ export const GetImportResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", @@ -1561,7 +1606,7 @@ export const UploadImportPartResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -1581,6 +1626,21 @@ export const UploadImportPartResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", @@ -1821,7 +1881,7 @@ export const ApplyImportResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -1841,6 +1901,21 @@ export const ApplyImportResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", @@ -2016,7 +2091,7 @@ export const GetImportVerificationResponse = zod.object({ code: zod .string() .describe( - "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. A later OpenBot may add a code; show the message.", + "isolated-bot-made-ordinary: OpenBot Cloud has no isolated computers, so a Bot that had one runs on an ordinary one. business-plan-feature-left-out: the feature needs the Business plan and this organization isn't on it. model-key-kept-existing: the person already had an AI connection here, which was kept. model-key-not-brought: the person chose not to bring a model key. item-skipped: one item couldn't be imported; message says which and why. bot-key-not-brought: the key a Bot's address sits behind couldn't come across, so the Bot needs it set again here; bots names each one. A later OpenBot may add a code; show the message.", ), kind: zod .string() @@ -2036,6 +2111,21 @@ export const GetImportVerificationResponse = zod.object({ .describe( "The names of the items, such as the Bots, when there are a few.", ), + bots: zod + .array( + zod.object({ + id: zod + .string() + .describe( + "The Bot's id in the organization the move went into.", + ), + name: zod.string().describe("The Bot's name."), + }), + ) + .optional() + .describe( + "The Bots the note is about, by their id here, so a client can open each one. Only on a note about Bots that need something done (bot-key-not-brought); absent otherwise.", + ), }) .describe( "Something that moved differently, or not at all, and why, in a sentence a person reads.", diff --git a/mobile/src/api/generated/bots/bots.ts b/mobile/src/api/generated/bots/bots.ts index 09d6d5c986..aa96c3e99e 100644 --- a/mobile/src/api/generated/bots/bots.ts +++ b/mobile/src/api/generated/bots/bots.ts @@ -381,6 +381,25 @@ export const revokeBotCallbackToken = async ( ); }; +export const getRemoveBotKeyUrl = (organizationId: string, botId: string) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/bots/${encodeURIComponent(String(botId))}/remove-key`; +}; + +/** + * Stop sending a key to the address a Bot runs at, and retire the key so it can't be read or used again. Its runs then reach the address with no key. Setting or replacing a key is updateBot's auth. Only whoever may manage the Bot may remove it. Removing a key that is not there changes nothing. + * @summary Remove a Bot's key + */ +export const removeBotKey = async ( + organizationId: string, + botId: string, + options?: Parameters[1], +): Promise => { + return apiRequest(getRemoveBotKeyUrl(organizationId, botId), { + ...options, + method: "POST", + }); +}; + export const getReportBotDeclineUrl = ( organizationId: string, botId: string, diff --git a/mobile/src/api/generated/model/bot.ts b/mobile/src/api/generated/model/bot.ts index 4f29bb8f04..efbc3cab94 100644 --- a/mobile/src/api/generated/model/bot.ts +++ b/mobile/src/api/generated/model/bot.ts @@ -38,7 +38,7 @@ export interface Bot { * @nullable */ endpoint: string | null; - /** Whether a key is set for its address. Never the key. */ + /** Whether a key is set for its address. Never the key. Set or replace it with updateBot's auth, and remove it with removeBotKey. A run its address refuses with 401 or 403 ends in a RUN_ERROR whose code is BOT_KEY_REFUSED, so a client can offer the way to this Bot's key. */ hasAuth: boolean; /** Whether it holds a credential for calling OpenBot's tools back. Never the credential. */ hasCallbackToken: boolean; From c6ab2f31114f5fab6ccd0190b0b2d567cd9174f9 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Mon, 30 Nov 2026 13:11:05 -0800 Subject: [PATCH 008/224] Ship the 1Password fill turned off unless OPENBOT_DESKTOP_ONEPASSWORD is set OpenBot Desktop now answers that it cannot fill from 1Password unless the environment variable OPENBOT_DESKTOP_ONEPASSWORD is 1 or true when it starts. While it is off the sign-in form does not offer the fill, every fill and picker command refuses, the 1Password helper is never started, and the menus carry no 1Password item. The variable is read in one place, once per launch. The docs say how to turn it on for an app opened from Finder: launchctl setenv OPENBOT_DESKTOP_ONEPASSWORD 1, then reopen the app. --- desktop/src-tauri/src/connected_ipc_tests.rs | 10 +- desktop/src-tauri/src/desktop_onepassword.rs | 121 ++++++++++- desktop/src-tauri/src/main.rs | 9 +- .../src-tauri/src/onepassword_ipc_tests.rs | 201 ++++++++++++++++++ docs/how-openbot-works.md | 15 ++ 5 files changed, 346 insertions(+), 10 deletions(-) diff --git a/desktop/src-tauri/src/connected_ipc_tests.rs b/desktop/src-tauri/src/connected_ipc_tests.rs index 69dbdf5220..00faec6097 100644 --- a/desktop/src-tauri/src/connected_ipc_tests.rs +++ b/desktop/src-tauri/src/connected_ipc_tests.rs @@ -972,13 +972,13 @@ mod connected_ipc { let built = &menus[menus.find(entries).unwrap()..]; let branches = built.find("if connected {").unwrap(); let entry = built - .find("fill_menu_entry(") + .find("resume_menu_entry(") .unwrap_or_else(|| panic!("{entries} lacks Allow 1Password Fills Again")); assert!(entry < branches, "{entries}: read before the branches split"); - // Offered only while paused: the gate's own answer, as it is, is the argument. + // Offered only while paused and turned on: `resume_menu_entry` asks the gate and the switch. assert!( built[entry..] - .starts_with("fill_menu_entry(desktop_onepassword::gate(app).is_paused())"), + .starts_with("resume_menu_entry(app)"), "{entries}: offered only while paused: {}", &built[entry..entry + 80] ); @@ -1016,6 +1016,10 @@ mod connected_ipc { assert_eq!( statements, [ + "// Nothing of 1Password is offered while fills are turned off, so a stale menu lifts nothing.", + "if !desktop_onepassword::enabled(app) {", + "return;", + "}", "desktop_onepassword::gate(app).resume();", "desktop_onepassword::menu_refresh(app).now();" ], diff --git a/desktop/src-tauri/src/desktop_onepassword.rs b/desktop/src-tauri/src/desktop_onepassword.rs index 1cf86d09b1..03a525db4b 100644 --- a/desktop/src-tauri/src/desktop_onepassword.rs +++ b/desktop/src-tauri/src/desktop_onepassword.rs @@ -64,6 +64,9 @@ pub(crate) struct State { picker: Picker, /// The bundled helper, once a fill needed it (`vault`): None in a build without one. helper: OnceLock>>, + /// Whether 1Password fills are turned on for this run (`enabled`): read from the environment + /// once, the first time anything asks. + enabled: OnceLock, /// Who rebuilds the menus when fills pause or are allowed again: None is the app's own /// (`menu_refresh`); a test sets one that records each call. pub(crate) menu_refresh: Mutex>>, @@ -72,6 +75,41 @@ pub(crate) struct State { fakes: Mutex, } +/// The environment variable that turns 1Password fills on. Without it, or with any value but `1` or +/// `true`, the whole feature is off: the page is told fills are unavailable, every fill and picker +/// command refuses, the helper is never started and the menus carry no 1Password entry. +pub(crate) const ENABLE_ENV: &str = "OPENBOT_DESKTOP_ONEPASSWORD"; + +/// Whether `value`, the variable's value, turns fills on. The same spellings `COPILOTKIT_TELEMETRY_DISABLED` +/// takes, in any case. +fn turned_on(value: Option) -> bool { + value + .and_then(|value| value.into_string().ok()) + .is_some_and(|value| matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true")) +} + +/// Whether 1Password fills are turned on for this run. The one place `ENABLE_ENV` is read, when +/// first asked (`start` asks at launch) and kept for the run: turning it on or off takes a relaunch. +/// A test puts its own answer in `Fakes`; without one, a test build reads the environment as any +/// other. +pub(crate) fn enabled(app: &tauri::AppHandle) -> bool { + #[cfg(test)] + if let Some(on) = fakes(app).enabled { + return on; + } + *app.state::() + .onepassword + .enabled + .get_or_init(|| { + let on = turned_on(std::env::var_os(ENABLE_ENV)); + log::info!( + "[1password] fills are {} ({ENABLE_ENV}).", + if on { "on" } else { "off" } + ); + on + }) +} + /// The menu item that lifts a pause: Allow 1Password Fills Again. pub(crate) const RESUME_FILLS: &str = "allow-onepassword-fills"; @@ -80,6 +118,16 @@ pub(crate) fn fill_menu_entry(paused: bool) -> Option<(&'static str, &'static st paused.then_some((RESUME_FILLS, "Allow 1Password Fills Again")) } +/// The same for the app's own menus: nothing at all while fills are turned off. +pub(crate) fn resume_menu_entry( + app: &tauri::AppHandle, +) -> Option<(&'static str, &'static str)> { + if !enabled(app) { + return None; + } + fill_menu_entry(gate(app).is_paused()) +} + /// How the 1Password code asks for the menus to be rebuilt. The app's own rebuilds them now /// (`refresh_menus`), or from a thread after `delay`; a test's records each call. pub(crate) trait MenuRefresh: Send + Sync { @@ -154,6 +202,9 @@ pub(crate) fn gate(app: &tauri::AppHandle) -> Arc(app: &tauri::AppHandle) { + if !enabled(app) { + return; + } if let Some(d) = gate(app).pause_remaining() { menu_refresh(app).after(d); } @@ -1117,6 +1168,8 @@ pub(crate) struct Fakes { pub(crate) vault: Option>, pub(crate) server: Option>, pub(crate) ui: Option>, + /// Whether fills are turned on (`enabled`). None reads the environment, as a release does. + pub(crate) enabled: Option, } #[cfg(test)] @@ -1156,6 +1209,9 @@ fn vault(app: &tauri::AppHandle) -> Option(app: &tauri::AppHandle) -> Available { + if !enabled(app) { + return Available { available: false }; + } #[cfg(test)] if let Some(vault) = fakes(app).vault { return Available { @@ -1410,6 +1466,9 @@ pub(crate) async fn fill_now( app: tauri::AppHandle, request_id: String, ) -> Result { + if !enabled(&app) { + return Err(Refusal::Unavailable.said()); + } tauri::async_runtime::spawn_blocking(move || { let gate = gate(&app); let was_paused = gate.is_paused(); @@ -1434,11 +1493,13 @@ pub(crate) async fn fill_now( /// Every picker command answers only the picker window, from the app's own local page: a remote /// origin cannot reach an app command at all, and no other window of this app may answer a fill. fn from_picker(window: &tauri::WebviewWindow) -> Result<(), String> { - if window.label() == PICKER { - Ok(()) - } else { - Err("Only OpenBot Desktop's 1Password window may ask this.".into()) + if window.label() != PICKER { + return Err("Only OpenBot Desktop's 1Password window may ask this.".into()); + } + if !enabled(window.app_handle()) { + return Err(Refusal::Unavailable.said()); } + Ok(()) } /// What the picker window shows now. Asked once when its page loads (twice in development, where @@ -1798,6 +1859,54 @@ mod tests { } } + /// Fills turned on for `app`, as the environment variable would. + fn turn_on(app: &tauri::App) { + use_fakes_for_test( + app.handle(), + Fakes { + enabled: Some(true), + ..Default::default() + }, + ); + } + + /// Only `1` and `true` (any case, spaces around) turn fills on; unset, empty and every other + /// value leave them off. + #[test] + fn only_one_or_true_turns_fills_on() { + let value = |v: &str| Some(std::ffi::OsString::from(v)); + for on in ["1", "true", "TRUE", "True", " 1 ", "true\n"] { + assert!(turned_on(value(on)), "{on:?}"); + } + for off in ["", "0", "false", "yes", "on", "2", "truee"] { + assert!(!turned_on(value(off)), "{off:?}"); + } + assert!(!turned_on(None)); + } + + /// With fills off, nothing creates the helper and a saved pause is not loaded or shown. + #[test] + fn with_fills_off_the_helper_is_never_created() { + let app = app(); + use_fakes_for_test( + app.handle(), + Fakes { + enabled: Some(false), + ..Default::default() + }, + ); + start(app.handle()); + assert_eq!(available_now(app.handle()), Available { available: false }); + assert_eq!( + tauri::async_runtime::block_on(fill_now(app.handle().clone(), "r1".into())).map(|_| ()), + Err(Refusal::Unavailable.said()) + ); + let onepassword = &app.state::().onepassword; + assert!(onepassword.helper.get().is_none(), "the helper was created"); + assert!(onepassword.gate.get().is_none(), "the gate was loaded"); + assert_eq!(resume_menu_entry(app.handle()), None); + } + /// The fill that pauses every fill asks for the menus now, and again when the pause ends by /// itself (60 minutes on the gate's own clock); fills before it and a fill refused as paused /// ask for nothing. @@ -1819,6 +1928,7 @@ mod tests { vault: Some(Arc::new(NeverAsked)), server: Some(Arc::new(PendingServer)), ui: Some(Arc::new(Cancels)), + enabled: Some(true), }, ); let fill = |id: &str| { @@ -1896,6 +2006,7 @@ mod tests { vault: Some(Arc::new(Panics)), server: Some(Arc::new(PendingServer)), ui: Some(Arc::new(Continues)), + enabled: Some(true), }, ); for id in ["r1", "r2", "r3"] { @@ -1920,6 +2031,7 @@ mod tests { pause(&Arc::new(FillGate::load(file.clone(), move || earlier))); let app = app(); + turn_on(&app); let loaded = Arc::new(FillGate::load(file, move || at)); assert!(app.state::().onepassword.gate.set(loaded).is_ok()); let refreshes = record_refreshes(&app); @@ -1927,6 +2039,7 @@ mod tests { assert_eq!(refreshes.calls(), ["after 2400s"]); let app = self::app(); + turn_on(&app); let unpaused_folder = config_folder("onepassword-gate-saved-unpaused"); let unpaused = unpaused_folder.join(GATE_FILE); let loaded = Arc::new(FillGate::load(unpaused, move || at)); diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 28de2947a2..ff739f4695 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -13915,6 +13915,10 @@ fn chose(app: &tauri::AppHandle, item: &str) { /// enter, and rebuild the menus without the item. Its own function, over any runtime, so a test can /// run what `chose` runs: `chose` itself takes the app's own runtime. fn resume_onepassword_fills(app: &tauri::AppHandle) { + // Nothing of 1Password is offered while fills are turned off, so a stale menu lifts nothing. + if !desktop_onepassword::enabled(app) { + return; + } desktop_onepassword::gate(app).resume(); desktop_onepassword::menu_refresh(app).now(); } @@ -14236,8 +14240,7 @@ fn install_menus(app: &tauri::AppHandle) -> tauri::Result< let tray_entries = || -> tauri::Result>> { let icon = |name: &str| menu_icon(name, dark); // Only while 1Password fills are paused, in both branches below. - let resume = - desktop_onepassword::fill_menu_entry(desktop_onepassword::gate(app).is_paused()); + let resume = desktop_onepassword::resume_menu_entry(app); if connected { let mut entries = vec![ MenuEntry::Icon(IconMenuItem::with_id( @@ -14374,7 +14377,7 @@ fn install_menus(app: &tauri::AppHandle) -> tauri::Result< )?)); // Only while 1Password fills are paused, connected or not. entries.extend( - desktop_onepassword::fill_menu_entry(desktop_onepassword::gate(app).is_paused()) + desktop_onepassword::resume_menu_entry(app) .map(resume_fills) .transpose()?, ); diff --git a/desktop/src-tauri/src/onepassword_ipc_tests.rs b/desktop/src-tauri/src/onepassword_ipc_tests.rs index af0ada5c6f..6689350246 100644 --- a/desktop/src-tauri/src/onepassword_ipc_tests.rs +++ b/desktop/src-tauri/src/onepassword_ipc_tests.rs @@ -129,6 +129,14 @@ mod onepassword_ipc { .unwrap() }); *app.state::().setup_url.lock().unwrap() = Some(SETUP.into()); + // Fills are off unless turned on: the page tests turn them on, and say so when they test it off. + desktop_onepassword::use_fakes_for_test( + app.handle(), + desktop_onepassword::Fakes { + enabled: Some(true), + ..Default::default() + }, + ); let config = temp_root("openbot-onepassword-config"); std::fs::create_dir_all(&config).unwrap(); desktop_connected::use_for_test( @@ -1418,6 +1426,7 @@ mod onepassword_ipc { vault: None, server: Some(server.clone()), ui: Some(ui.clone()), + enabled: Some(true), }); let unavailable = Err(serde_json::json!(Refusal::Unavailable.said())); let fill = serde_json::json!({ "signInRequestId": "r1" }); @@ -1471,6 +1480,192 @@ mod onepassword_ipc { assert_eq!(ui.shown(), Vec::::new()); } + /// 1Password that records that it was ever reached, by any call. + #[derive(Default)] + struct CountingVault { + reached: std::sync::atomic::AtomicUsize, + } + + impl CountingVault { + fn reached(&self) -> usize { + self.reached.load(std::sync::atomic::Ordering::SeqCst) + } + } + + impl OnePassword for CountingVault { + fn available(&self) -> bool { + self.reached.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + true + } + + fn list(&self, _: &str, _: Instant) -> Result, Refusal> { + self.reached.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(github_logins_and_one_elsewhere()) + } + + fn resolve(&self, _: &str, _: &str, _: &str, _: Instant) -> Result { + self.reached.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Err(Refusal::Refused) + } + } + + /// With `OPENBOT_DESKTOP_ONEPASSWORD` unset (`enabled: None` reads the environment), through + /// the real IPC and its ACL: the page is told fills are unavailable, a fill is refused with + /// the desktop's own sentence, and nothing is reached: not 1Password (the helper), not the + /// server, not a window, and the shell's helper is never even created. + #[test] + fn with_the_variable_unset_the_page_is_told_unavailable_and_nothing_is_reached() { + assert!( + std::env::var_os(desktop_onepassword::ENABLE_ENV).is_none(), + "this test needs {} unset", + desktop_onepassword::ENABLE_ENV + ); + let shell = Picking::paging(); + let vault = Arc::new(CountingVault::default()); + let server = Arc::new(RecordingServer::default()); + let ui = AnsweringUi::new(true); + shell.use_fakes(desktop_onepassword::Fakes { + vault: Some(vault.clone()), + server: Some(server.clone()), + ui: Some(ui.clone()), + enabled: None, + }); + let page = format!("{OWNED}/settings/computer"); + assert_eq!( + shell.page(&page, AVAILABLE, serde_json::json!({})), + Ok(serde_json::json!({ "available": false })) + ); + assert_eq!( + shell.page(&page, FILL, serde_json::json!({ "signInRequestId": "r1" })), + Err(serde_json::json!(Refusal::Unavailable.said())) + ); + assert_eq!(vault.reached(), 0, "1Password was reached"); + assert_eq!(server.requested(), Vec::::new()); + assert_eq!(ui.shown(), Vec::::new()); + assert!( + shell.app.get_webview_window(PICKER).is_none(), + "the 1Password window opened" + ); + assert!(!desktop_onepassword::enabled(shell.app.handle())); + } + + /// The real environment, in a process of its own with the variable set to each value: only `1` + /// and `true` turn fills on, and the page is then told available. The child asks the page's + /// command through the real IPC; it prints what it was told. + #[test] + fn the_variable_in_a_real_process_turns_fills_on_only_when_set() { + const CHILD: &str = "OPENBOT_TEST_ONEPASSWORD_ENV_CHILD"; + if std::env::var_os(CHILD).is_some() { + let shell = Picking::paging(); + shell.use_fakes(desktop_onepassword::Fakes { + vault: Some(Arc::new(CountingVault::default())), + server: Some(Arc::new(RecordingServer::default())), + ui: Some(AnsweringUi::new(false)), + enabled: None, + }); + let told = shell.page(&format!("{OWNED}/chat"), AVAILABLE, serde_json::json!({})); + println!("the page was told {}", serde_json::to_string(&told).unwrap()); + return; + } + for (value, expected) in [ + (None, false), + (Some(""), false), + (Some("0"), false), + (Some("1"), true), + (Some("true"), true), + ] { + let mut child = std::process::Command::new(std::env::current_exe().unwrap()); + child + .args([ + "tests::onepassword_ipc::the_variable_in_a_real_process_turns_fills_on_only_when_set", + "--exact", + "--nocapture", + "--test-threads=1", + ]) + .env(CHILD, "1") + .env_remove(desktop_onepassword::ENABLE_ENV); + if let Some(value) = value { + child.env(desktop_onepassword::ENABLE_ENV, value); + } + let output = child.output().unwrap(); + let said = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.status.success(), "{said}"); + let line = said + .lines() + .find_map(|line| line.find("the page was told ").map(|at| &line[at..])) + .unwrap_or_else(|| panic!("{said}")); + assert_eq!( + line, + format!("the page was told {{\"Ok\":{{\"available\":{expected}}}}}"), + "{:?}: {said}", + value + ); + } + } + + /// The same with the switch explicitly off, and then on: off, the picker's commands refuse + /// too and the menu has no 1Password entry; on, the page is told available and a fill runs as + /// it always did. + #[test] + fn the_switch_turns_the_whole_feature_off_and_on() { + let shell = Picking::paging(); + let vault = Arc::new(CountingVault::default()); + let off = |enabled: bool| desktop_onepassword::Fakes { + vault: Some(vault.clone()), + server: Some(Arc::new(RecordingServer::default())), + ui: Some(AnsweringUi::new(false)), + enabled: Some(enabled), + }; + let page = format!("{OWNED}/chat"); + let fill = serde_json::json!({ "signInRequestId": "r1" }); + + shell.use_fakes(off(false)); + assert_eq!( + shell.page(&page, AVAILABLE, serde_json::json!({})), + Ok(serde_json::json!({ "available": false })) + ); + assert_eq!( + shell.page(&page, FILL, fill.clone()), + Err(serde_json::json!(Refusal::Unavailable.said())) + ); + let picker = tauri::WebviewWindowBuilder::new(&shell.app, PICKER, Default::default()) + .build() + .unwrap(); + for cmd in [ + "onepassword_session", + "onepassword_begin_answer", + "onepassword_pick_answer", + "onepassword_forget", + ] { + assert_eq!( + ask( + &picker, + SETUP, + cmd, + serde_json::json!({ "fill": 1, "account": null, "key": null, "remember": false, "site": SITE }), + ), + Err(serde_json::json!(Refusal::Unavailable.said())), + "{cmd} answered with fills off" + ); + } + assert_eq!(desktop_onepassword::resume_menu_entry(shell.app.handle()), None); + assert_eq!(vault.reached(), 0, "1Password was reached"); + + shell.use_fakes(off(true)); + assert_eq!( + shell.page(&page, AVAILABLE, serde_json::json!({})), + Ok(serde_json::json!({ "available": true })) + ); + assert_eq!( + shell.page(&page, FILL, fill), + Err(serde_json::json!(Refusal::NotFilled.said())) + ); + } + /// Threats, through the real IPC: the site comes only from the server's copy of the request, /// whatever the page sends beside the id; only matching logins are offered; and the page gets /// the request's status and outcome, never the value, the username, a title or an id. The @@ -1485,6 +1680,7 @@ mod onepassword_ipc { vault: Some(vault.clone()), server: Some(server.clone()), ui: Some(ui.clone()), + enabled: Some(true), }); let page = format!("{OWNED}/chat"); assert_eq!( @@ -1555,6 +1751,7 @@ mod onepassword_ipc { vault: Some(vault.clone()), server: Some(Arc::new(RecordingServer::default())), ui: None, + enabled: Some(true), }); let filling = shell.page_filling("r1"); assert_eq!( @@ -1587,6 +1784,7 @@ mod onepassword_ipc { vault: Some(no_login.clone()), server: Some(Arc::new(RecordingServer::default())), ui: None, + enabled: Some(true), }); let filling = shell.page_filling("r2"); shell.showing("begin"); @@ -1625,6 +1823,7 @@ mod onepassword_ipc { vault: Some(vault.clone()), server: Some(server.clone()), ui: Some(ui.clone()), + enabled: Some(true), }); let page = format!("{OWNED}/chat"); let fill = |id: &str| shell.page(&page, FILL, serde_json::json!({ "signInRequestId": id })); @@ -1668,6 +1867,7 @@ mod onepassword_ipc { vault: Some(RecordingVault::new(github_logins_and_one_elsewhere())), server: Some(Arc::new(RecordingServer::default())), ui: Some(ui.clone()), + enabled: Some(true), }); let menus = Arc::new(CountingMenus::default()); *shell @@ -2314,6 +2514,7 @@ mod onepassword_ipc { vault: Some(vault.clone()), server: None, ui: Some(ui.clone()), + enabled: Some(true), }); (vault, ui) } diff --git a/docs/how-openbot-works.md b/docs/how-openbot-works.md index 0a0b29ffe5..16e13da47d 100644 --- a/docs/how-openbot-works.md +++ b/docs/how-openbot-works.md @@ -117,6 +117,21 @@ When a Bot asks you to sign in to a site, the sign-in form can fill your login f instead. Only OpenBot Desktop offers this. It uses the 1Password app on your computer, and it starts on Macs with Apple silicon running macOS 12 or later. +This is off by default. OpenBot Desktop shows **Fill from 1Password** only when the environment +variable `OPENBOT_DESKTOP_ONEPASSWORD` is `1` or `true` for the app. An app you open from Finder or +the Dock does not read your shell's variables. To turn it on for that app, run this command in +Terminal, then quit OpenBot Desktop and open it again: + +```sh +launchctl setenv OPENBOT_DESKTOP_ONEPASSWORD 1 +``` + +The setting lasts until you log out or restart your Mac. To turn it off, run +`launchctl unsetenv OPENBOT_DESKTOP_ONEPASSWORD` and open the app again. OpenBot Desktop reads the +variable once, when it starts. While it is off, the sign-in form does not offer 1Password, the +1Password helper never starts, and the menu has no 1Password item. When you run the app from a +terminal, `OPENBOT_DESKTOP_ONEPASSWORD=1` before the command is enough. + Before the first fill, open 1Password and turn on Settings → Developer → Integrate with 1Password SDKs. Choose **Fill from 1Password** on the sign-in form. Then: From 8c22d0926fcf8d74d4224339ef205a674b032f73 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 15:00:29 -0800 Subject: [PATCH 009/224] Desktop: confirm only apps from the directory when the window is back (#2557) The window confirmed every consent when it was back in front, including apps OpenBot signs the person in to itself, which its own sign-in page records before the person is back; that confirm asks the broker and was refused with a 400 after every one of those sign-ins. It now confirms only apps from the directory, and still reads every list again. --- app/src/lib/plugins/confirm-on-return.ts | 25 ++++++- app/tests/desktop-confirm-on-return.test.ts | 82 +++++++++++++++++++-- 2 files changed, 96 insertions(+), 11 deletions(-) diff --git a/app/src/lib/plugins/confirm-on-return.ts b/app/src/lib/plugins/confirm-on-return.ts index 5073cec2fe..edf0f37358 100644 --- a/app/src/lib/plugins/confirm-on-return.ts +++ b/app/src/lib/plugins/confirm-on-return.ts @@ -1,6 +1,7 @@ import type { QueryClient } from "@tanstack/react-query"; -import { appSetupQueryOptions } from "@/lib/apps/queries"; +import { appSetupQueryOptions, appsQueryOptions } from "@/lib/apps/queries"; import { desktopShell } from "@/lib/desktop/shell"; +import { fromDirectory } from "./provider-vocabulary"; import { pluginKeys } from "./queries"; /** The consents waiting for the window to be back in front, by app key, with how each is confirmed. */ @@ -39,14 +40,32 @@ export function confirmOnReturn( async function confirmPending(): Promise { const queryClient = client; - const confirms = [...pending.values()]; + const waiting = [...pending.entries()]; pending.clear(); client = null; - if (!queryClient || confirms.length === 0) return; + if (!queryClient || waiting.length === 0) return; const setup = await queryClient .fetchQuery(appSetupQueryOptions()) .catch(() => null); if (setup?.authorizesPerAction) return; + /* + * ONLY AN APP FROM THE DIRECTORY IS CONFIRMED. Its account is held by the service that signed the + * person in, so the window asks that service whether it is there. An app OpenBot signs the person + * in to itself (a catalogue app, or a server added by its address) is recorded by OpenBot's own + * sign-in page before the person is even back, and there is nothing to confirm: asking was refused + * as "That app doesn't connect this way." after every one of those sign-ins, though each had + * connected. Where the list of apps can't be read, every consent is confirmed, as before. + */ + const apps = await queryClient + .fetchQuery(appsQueryOptions()) + .catch(() => null); + const confirms = waiting + .filter( + ([serverId]) => + apps === null || + apps.some((app) => app.id === serverId && fromDirectory(app)), + ) + .map(([, ask]) => ask); // A refusal is not the window's to report: the lists read again say whether it is connected. await Promise.allSettled(confirms.map((ask) => ask())); await queryClient.invalidateQueries({ queryKey: pluginKeys.all }); diff --git a/app/tests/desktop-confirm-on-return.test.ts b/app/tests/desktop-confirm-on-return.test.ts index 7c4d910ee4..a1eb1979a4 100644 --- a/app/tests/desktop-confirm-on-return.test.ts +++ b/app/tests/desktop-confirm-on-return.test.ts @@ -44,26 +44,70 @@ function inDesktopWindow() { } /** - * A deployment where Gmail is consented to: the connect press answers the consent page, and the - * confirm records the account (the app says yes), so the connections read lists it from then on. + * A deployment where Gmail, from the directory, is consented to: the connect press answers the + * consent page, and the confirm records the account (the app says yes), so the connections read lists + * it from then on. + * + * Notion is an app OpenBot signs the person in to itself, as the server does: its sign-in page + * records the connection before the person is back, and a confirm of it is refused, because there is + * no broker account to ask about. */ function deployment(options: { authorizesPerAction?: boolean } = {}) { - const server = { confirms: [] as string[], recorded: false }; + const server = { + confirms: [] as string[], + refused: [] as string[], + recorded: [] as string[], + }; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const call = connectionsCall(input, init); if (call?.operation === "list") - return connectionPage(server.recorded ? [{ serverId: "gmail" }] : []); - if (call?.operation === "connect") + return connectionPage(server.recorded.map((serverId) => ({ serverId }))); + if (call?.operation === "connect") { + // OpenBot's own sign-in page records an app it signs the person in to as they finish there. + if (call.appId === "notion") server.recorded.push("notion"); return startResponse({ authorizationUrl: CONSENT_URL }); + } if (call?.operation === "confirm") { + if (call.appId === "notion") { + server.refused.push("notion"); + return new Response( + JSON.stringify({ + type: "https://open.bot/errors/invalid-argument", + title: "Invalid argument.", + status: 400, + detail: "That app doesn't connect this way.", + code: "INVALID_ARGUMENT", + }), + { + status: 400, + headers: { "content-type": "application/problem+json" }, + }, + ); + } server.confirms.push(call.appId ?? ""); - server.recorded = true; + server.recorded.push(call.appId ?? ""); return confirmationResponse(true); } const apps = answerAppsApi(input, init, { composioConfigured: true, authorizesPerAction: options.authorizesPerAction ?? false, provider: options.authorizesPerAction ? "arcade" : "composio", + servers: [ + { + id: "gmail", + title: "Gmail", + url: "composio://gmail", + provenance: "composio", + authScheme: "OAUTH2", + }, + { + id: "notion", + title: "Notion", + url: "https://mcp.notion.com/mcp", + provenance: "first-party", + signIn: true, + }, + ], }); if (apps) return apps; return new Response(null, { status: 404 }); @@ -72,7 +116,7 @@ function deployment(options: { authorizesPerAction?: boolean } = {}) { } /** A list of the person's connections on screen, and a Connect pressed from it. */ -async function connectFromAList() { +async function connectFromAList(app = "gmail") { const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, }); @@ -84,7 +128,7 @@ async function connectFromAList() { const start = await new MutationObserver( client, connectAccountMutationOptions("settings"), - ).mutate("gmail"); + ).mutate(app); expect(start).toEqual({ authorizationUrl: CONSENT_URL }); const listed = () => (list.getCurrentResult().data?.connections ?? []).map( @@ -114,6 +158,28 @@ test("in the Desktop window, a connect started from a list is confirmed once the window.dispatchEvent(new Event("focus")); await settle(); expect(server.confirms).toEqual(["gmail"]); + expect(server.refused).toEqual([]); + } finally { + stop(); + } +}); + +/* + * Found on OpenBot Cloud, 30 Nov: every sign-in to an app OpenBot signs the person in to itself + * (Neon, Notion, Vercel, Clay and others) was followed by a confirm the server refused with a 400, + * though each had connected. Current Desktop sent it as well as older ones. + */ +test("in the Desktop window, an app OpenBot signs the person in to itself is not confirmed, and the list shows it", async () => { + inDesktopWindow(); + const server = deployment(); + const { listed, stop } = await connectFromAList("notion"); + try { + window.dispatchEvent(new Event("focus")); + // The lists are read again, and say it is connected. + await waitFor(() => expect(listed()).toEqual(["notion"])); + await settle(); + expect(server.refused).toEqual([]); + expect(server.confirms).toEqual([]); } finally { stop(); } From 1f006b1b4e97c8d49e853203924af7e2c472b152 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 15:16:17 -0800 Subject: [PATCH 010/224] Stop asking for a task this OpenBot doesn't have, and draw no card for it (#2556) A conversation moved from another OpenBot carries the cards of tasks that stayed behind. Each card asked for its task on every mount, retried, and asked again on every work event, and read Working for ever. A task's own not-found is now an answer: asked once, never read again, and its card, needs-you frame and thread link draw nothing, while the Bot's own words stay. --- app/src/components/tasks/task-steer.tsx | 2 + app/src/components/tasks/task-thread.tsx | 25 +++++-- app/src/lib/channels/use-channel-events.ts | 4 +- app/src/lib/tasks/queries.ts | 46 ++++++++++--- app/tests/task-thread.test.tsx | 78 ++++++++++++++++++++++ 5 files changed, 139 insertions(+), 16 deletions(-) diff --git a/app/src/components/tasks/task-steer.tsx b/app/src/components/tasks/task-steer.tsx index da4026dd11..25d71c1082 100644 --- a/app/src/components/tasks/task-steer.tsx +++ b/app/src/components/tasks/task-steer.tsx @@ -56,6 +56,8 @@ export function TaskSteer({ taskId }: { taskId: string }) { */ export function SteerLanded({ taskId }: { taskId: string }) { useEffect(() => { + // A task this OpenBot has no such task for is never asked about again (`taskQueryOptions`). + if (queryClient.getQueryData(taskKeys.one(taskId)) === null) return; void queryClient.invalidateQueries({ queryKey: taskKeys.one(taskId) }); }, [taskId]); return null; diff --git a/app/src/components/tasks/task-thread.tsx b/app/src/components/tasks/task-thread.tsx index 9b14c1d965..bd8e358e5d 100644 --- a/app/src/components/tasks/task-thread.tsx +++ b/app/src/components/tasks/task-thread.tsx @@ -315,14 +315,16 @@ export function TaskCard({ ...taskQueryOptions(taskId ?? ""), enabled: Boolean(taskId), }); - const state = cardState(taskId ? task.data : undefined); + const state = cardState(taskId ? (task.data ?? undefined) : undefined); const [stopError, setStopError] = useState(null); // The card's clock, once there is a task to time: every second while it works, and every half // minute otherwise. - const now = useNow( - state === "working" ? 1_000 : 30_000, - task.data !== undefined, - ); + const now = useNow(state === "working" ? 1_000 : 30_000, Boolean(task.data)); + /* + * A task this OpenBot has no such task for (a conversation moved from another OpenBot names the + * tasks that stayed there): no card, rather than one that says Working for ever. + */ + if (taskId && task.data === null) return null; if (refusal) return ( @@ -350,7 +352,9 @@ export function TaskCard({ ) : null } waiting={ - tryingAgainAt(task.data, state, now) !== undefined ? "retry" : undefined + tryingAgainAt(task.data ?? undefined, state, now) !== undefined + ? "retry" + : undefined } action={ channelId ? ( @@ -477,7 +481,12 @@ export function TaskReport({ const task = useQuery(taskQueryOptions(taskId)); const title = task.data?.title; const channelId = task.data?.channelId; - const live = cardState(task.data); + const live = cardState(task.data ?? undefined); + /* + * A task this OpenBot has no such task for: the Bot's words stay, as it said them, with no task + * framed around them, no state that can never change, and no way into a thread that isn't here. + */ + if (task.data === null) return
{children}
; if (kind === "result") { /* * A result that left the task waiting on the person (an app's Request access card drawn under @@ -666,6 +675,8 @@ export function ThreadLinks({ threads }: { threads: LinkedThread[] }) { function ThreadLink({ thread }: { thread: LinkedThread }) { const task = useQuery(taskQueryOptions(thread.taskId)); + // A task this OpenBot has no such task for has no thread here to lead into. + if (task.data === null) return null; const state = cardState(task.data ?? { status: thread.status as TaskStatus }); return (
  • diff --git a/app/src/lib/channels/use-channel-events.ts b/app/src/lib/channels/use-channel-events.ts index bceed0def0..95bb9cd325 100644 --- a/app/src/lib/channels/use-channel-events.ts +++ b/app/src/lib/channels/use-channel-events.ts @@ -407,7 +407,9 @@ function readAgainWhenLanded(queryClient: QueryClient, query: Query): void { function readTasksOfConversation(queryClient: QueryClient, channelId: string) { const cache = queryClient.getQueryCache(); for (const query of cache.findAll({ queryKey: taskKeys.ones })) { - const card = query.state.data as BotTask | undefined; + const card = query.state.data as BotTask | null | undefined; + // A task this OpenBot has no such task for (`taskQueryOptions`) is never asked about again. + if (card === null) continue; // A task with no conversation that asked for it (a check-in's) is read on any change, as before. if ( card?.originChannelId && diff --git a/app/src/lib/tasks/queries.ts b/app/src/lib/tasks/queries.ts index e285ef9e7a..8853822035 100644 --- a/app/src/lib/tasks/queries.ts +++ b/app/src/lib/tasks/queries.ts @@ -7,6 +7,7 @@ import { listTaskTurns, } from "@/lib/api/generated/tasks/tasks"; import { organizationId } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; /* * The person's tasks: what Start makes of an item a Bot's check-in found. Each runs in a conversation @@ -177,21 +178,50 @@ function workingOrigins(tasks: BotTask[]): string[] { export const delegatingConversationsQueryOptions = () => queryOptions({ ...taskListQueryOptions(), select: workingOrigins }); +/** + * Whether a refusal says this OpenBot has no such task for the person: the task's own not-found, + * never the organization's (a 404 `ORGANIZATION_NOT_FOUND`, which the query client answers for the + * whole app). + */ +export function taskNotFound(error: unknown): boolean { + return ( + error instanceof ClientError && + error.status === 404 && + error.code === "NOT_FOUND" + ); +} + /** * One task, as its card in the conversation that asked for it reads it: kept live while it works or * waits on the person, and left alone once it is done or couldn't finish. + * + * NULL IS AN ANSWER: THIS OPENBOT HAS NO SUCH TASK. A conversation can name a task that is not here: + * a conversation moved from another OpenBot carries its messages, and with them the cards of tasks + * that stayed behind. Read as a failure, such a task was asked for again by every card that drew it, + * on every mount and on every work event in any conversation, and its card said Working for ever. + * Answered as null it is asked once, never read again (`staleTime`), and its cards draw nothing. */ export const taskQueryOptions = (id: string) => queryOptions({ queryKey: taskKeys.one(id), - queryFn: async (): Promise => - botTaskOf( - ( - await getTask(organizationId(), id, { - fallback: "Couldn't load this task", - }) - ).task, - ), + queryFn: async (): Promise => { + try { + return botTaskOf( + ( + await getTask(organizationId(), id, { + fallback: "Couldn't load this task", + }) + ).task, + ); + } catch (error) { + if (taskNotFound(error)) return null; + throw error; + } + }, + staleTime: (query) => + query.state.status === "success" && query.state.data === null + ? Number.POSITIVE_INFINITY + : 0, refetchInterval: (query) => query.state.data && moving(query.state.data.status) ? LIVE_MS : false, }); diff --git a/app/tests/task-thread.test.tsx b/app/tests/task-thread.test.tsx index 9c9836f1fb..e287b2e16b 100644 --- a/app/tests/task-thread.test.tsx +++ b/app/tests/task-thread.test.tsx @@ -1103,3 +1103,81 @@ test("a task handed to an agent names it on its card and in its thread, and a ta await plain.findByText(/Sent from/); expect(plain.container.querySelector("[data-slot=task-agent]")).toBeNull(); }); + +/* + * Found on OpenBot Cloud, 30 Nov: a conversation moved in from another OpenBot carried the cards of + * tasks that stayed behind, so every read of them was refused as not found. Each card asked again on + * every mount and on every work event, and said Working for ever. + */ +test("a task this OpenBot has no such task for is asked about once, and its cards draw nothing", async () => { + // As the app is set up: a failed read is tried once more. + const client = new QueryClient({ + defaultOptions: { queries: { retry: 1 } }, + }); + const asked = () => + requests.filter((request) => request.endsWith("/tasks/task-moved")).length; + const conversation = ( + <> + + +

    Which venue should I book?

    +
    + + ); + const view = draw(conversation, client); + await view.findByText("Which venue should I book?"); + await waitFor(() => expect(asked()).toBe(1)); + // Past the retry's wait: no card that says Working for ever, and no Needs you frame. + await new Promise((resolve) => setTimeout(resolve, 1_500)); + expect(asked()).toBe(1); + expect(view.container.querySelector("[data-slot=task-card]")).toBeNull(); + expect(view.queryByText("Working")).toBeNull(); + expect(view.queryByText("Needs you")).toBeNull(); + expect(view.queryByRole("button", { name: /thread/ })).toBeNull(); + + // Drawn again, as scrolling the conversation does, it is not asked about again. + cleanup(); + const again = draw(conversation, client); + await again.findByText("Which venue should I book?"); + // Nor on a work event in its conversation. + act(() => + refreshTaskCards(client, { + channelId: "channel_moved", + lastMessage: null, + lastMessageAt: null, + lastMessageAgentId: null, + work: [], + workAt: "2026-11-30T19:13:17.000000Z", + }), + ); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + expect(asked()).toBe(1); + expect(again.container.querySelector("[data-slot=task-card]")).toBeNull(); +}, 15_000); + +test("a task's card stays when its read fails for a reason other than not found", async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + server.use( + http.get( + "*/api/v2/organizations/:organizationId/tasks/task-broken", + () => new HttpResponse(null, { status: 500 }), + { once: true }, + ), + ); + const view = draw( + , + client, + ); + // Not taken for a task that isn't here: the card stays. + await waitFor(() => + expect( + view.container.querySelector("[data-slot=task-card]"), + ).not.toBeNull(), + ); +}); From 11c7249fd409438b2efe692cda9f1222d1b1aeb3 Mon Sep 17 00:00:00 2001 From: Guido Vizoso Date: Mon, 30 Nov 2026 20:25:52 -0300 Subject: [PATCH 011/224] Connect more providers from the model picker, and a default model on New Bot (#2517) * Creating a Bot can name its default model, as changing one can * The model picker offers Connect more providers to whoever can connect one * New Bot can choose the Bot's default model * Who may connect a provider is asked when the picker opens, and the New Bot sheet offers no way out of itself * A Bot's default saves the model's own thinking level as the model's default, as a conversation's does * Tab from the model search reaches Connect more providers * Skins test: a centred OpenDuet page title sits 1px further right in Figtree --------- Co-authored-by: David McKay --- CHANGELOG.md | 5 + api/openapi.yaml | 58 +++---- api/openapi/bots.yaml | 58 ++++--- app/src/components/agents/new-bot-sheet.tsx | 44 +++++- .../components/bot-profile/default-model.tsx | 24 +-- .../channels/composer/model-picker.tsx | 96 ++++++++++-- .../components/settings/provider-pages.tsx | 9 +- app/src/lib/ai-connection/can-connect.ts | 36 +++++ app/src/lib/api/generated/bots/bots.zod.ts | 39 +++++ ...efaultModel.ts => botDefaultModelInput.ts} | 4 +- app/src/lib/api/generated/model/botFields.ts | 9 +- .../api/generated/model/createBotRequest.ts | 3 + app/src/lib/api/generated/model/index.ts | 2 +- app/src/lib/models/effort.ts | 24 +++ app/tests/bot-default-for.test.ts | 96 ++++++++++++ app/tests/can-connect-providers.test.tsx | 89 +++++++++++ app/tests/model-picker.test.tsx | 71 +++++++++ app/tests/new-bot-sheet.test.tsx | 142 ++++++++++++++++++ ...efaultModel.ts => botDefaultModelInput.ts} | 4 +- mobile/src/api/generated/model/botFields.ts | 9 +- .../api/generated/model/createBotRequest.ts | 3 + mobile/src/api/generated/model/index.ts | 2 +- 22 files changed, 719 insertions(+), 108 deletions(-) create mode 100644 app/src/lib/ai-connection/can-connect.ts rename app/src/lib/api/generated/model/{botFieldsDefaultModel.ts => botDefaultModelInput.ts} (78%) create mode 100644 app/tests/bot-default-for.test.ts create mode 100644 app/tests/can-connect-providers.test.tsx rename mobile/src/api/generated/model/{botFieldsDefaultModel.ts => botDefaultModelInput.ts} (78%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e3f68f87f..b7ccb4096a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **New Bot lets you choose its default model.** A Bot that runs here can start on the model you + pick when you make it, such as a design Bot on Claude Opus. Leave it alone and the Bot uses your + default, as before. You can still change it later in the Bot's Setup. +- **Connect more providers from the model picker.** The plus beside the model search opens + Settings → AI providers. It shows only to people who can connect one there. - **The Theme menu shows Light, Dark and System in a short window.** With little room above and below the Theme setting, as in a small or zoomed-in window, the menu cut off Dark. It now moves up or down to show all three, and scrolls when the window is too short for them. diff --git a/api/openapi.yaml b/api/openapi.yaml index 7b1eb57096..342b092041 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -26836,33 +26836,8 @@ components: instructions: $ref: '#/components/schemas/BotInstructions' defaultModel: - type: - - object - - 'null' - additionalProperties: false + $ref: '#/components/schemas/BotDefaultModelInput' description: A model from the connected provider and its thinking level. Null resets to the deployment default. Omit to keep the current setting. - required: - - model - - effort - properties: - model: - type: string - minLength: 1 - maxLength: 500 - pattern: \S - effort: - type: - - string - - 'null' - minLength: 1 - maxLength: 40 - pattern: \S - source: - type: string - minLength: 1 - maxLength: 40 - pattern: ^[a-z][a-z0-9-]*$ - description: Who serves the model, as the catalogue's connections name it (ModelCatalogueConnection source). The default applies for a person with a connection of that kind that can run. Omit for the default connection's. CreateBotRequest: description: 'A new Bot: a Bot''s fields, and the framework it is built on. One closed object, not BotFields with harness added in an allOf, because each closed part of an allOf would refuse the other''s fields.' type: object @@ -26889,6 +26864,9 @@ components: $ref: '#/components/schemas/BotIsolated' instructions: $ref: '#/components/schemas/BotInstructions' + defaultModel: + $ref: '#/components/schemas/BotDefaultModelInput' + description: The Bot's default model and thinking level, checked as updateBot checks it. Omit, or send null, for the deployment default. harness: type: string description: 'The framework an agent somebody runs themselves is built on, by its id in OpenBot''s harness list (shared/harnesses.json), which the server checks every create against. Empty means none was named, as for an agent somebody already runs. "byo-url" is not one: it names no framework. Kept only with an endpoint, with one exception: "langgraph-ts" sent with no endpoint asks for a Bot that runs inside OpenBot on OpenBot''s own LangGraph (TypeScript) engine, which is what the New Bot sheet sends. The deployment decides what each run uses: a Claude plan keeps the Claude Agent SDK engine, a ChatGPT plan signed in on OpenBot Desktop the OpenAI Agents SDK engine, and an administrator may switch new Bots back to the built-in agent.' @@ -29673,6 +29651,34 @@ components: minLength: 1 maxLength: 5000 description: New instructions for the starter Bot, 1 to 5000 characters once trimmed. Absent leaves them as they are; every other Bot ignores them. + BotDefaultModelInput: + type: + - object + - 'null' + additionalProperties: false + description: A model from the connected provider, as the model catalogue names it, and its thinking level. + required: + - model + - effort + properties: + model: + type: string + minLength: 1 + maxLength: 500 + pattern: \S + effort: + type: + - string + - 'null' + minLength: 1 + maxLength: 40 + pattern: \S + source: + type: string + minLength: 1 + maxLength: 40 + pattern: ^[a-z][a-z0-9-]*$ + description: Who serves the model, as the catalogue's connections name it (ModelCatalogueConnection source). The default applies for a person with a connection of that kind that can run. Omit for the default connection's. BotComputer: type: string enum: diff --git a/api/openapi/bots.yaml b/api/openapi/bots.yaml index aec24ffad4..7b5657ae92 100644 --- a/api/openapi/bots.yaml +++ b/api/openapi/bots.yaml @@ -1972,33 +1972,38 @@ components: instructions: $ref: '#/components/schemas/BotInstructions' defaultModel: - type: [object, 'null'] - additionalProperties: false + $ref: '#/components/schemas/BotDefaultModelInput' description: >- A model from the connected provider and its thinking level. Null resets to the deployment default. Omit to keep the current setting. - required: [model, effort] - properties: - model: - type: string - minLength: 1 - maxLength: 500 - pattern: \S - effort: - type: [string, 'null'] - minLength: 1 - maxLength: 40 - pattern: \S - source: - type: string - minLength: 1 - maxLength: 40 - pattern: ^[a-z][a-z0-9-]*$ - description: >- - Who serves the model, as the catalogue's connections name it - (ModelCatalogueConnection source). The default applies for a - person with a connection of that kind that can run. Omit for - the default connection's. + BotDefaultModelInput: + type: [object, 'null'] + additionalProperties: false + description: >- + A model from the connected provider, as the model catalogue names it, + and its thinking level. + required: [model, effort] + properties: + model: + type: string + minLength: 1 + maxLength: 500 + pattern: \S + effort: + type: [string, 'null'] + minLength: 1 + maxLength: 40 + pattern: \S + source: + type: string + minLength: 1 + maxLength: 40 + pattern: ^[a-z][a-z0-9-]*$ + description: >- + Who serves the model, as the catalogue's connections name it + (ModelCatalogueConnection source). The default applies for a + person with a connection of that kind that can run. Omit for + the default connection's. CreateBotRequest: description: >- A new Bot: a Bot's fields, and the framework it is built on. One closed @@ -2024,6 +2029,11 @@ components: $ref: '#/components/schemas/BotIsolated' instructions: $ref: '#/components/schemas/BotInstructions' + defaultModel: + $ref: '#/components/schemas/BotDefaultModelInput' + description: >- + The Bot's default model and thinking level, checked as updateBot + checks it. Omit, or send null, for the deployment default. harness: type: string description: >- diff --git a/app/src/components/agents/new-bot-sheet.tsx b/app/src/components/agents/new-bot-sheet.tsx index 2a9161cd18..f43879688f 100644 --- a/app/src/components/agents/new-bot-sheet.tsx +++ b/app/src/components/agents/new-bot-sheet.tsx @@ -17,10 +17,11 @@ import { useQuery, } from "@tanstack/react-query"; import { MotionConfig, motion, useReducedMotion } from "motion/react"; -import { Fragment, useEffect, useRef, useState } from "react"; +import { Fragment, type ReactNode, useEffect, useRef, useState } from "react"; import { CustomAgentCta } from "@/components/agents/custom-agent-cta"; import { HarnessMark } from "@/components/agents/harness-mark"; import AgentOrb from "@/components/agents/orb/agent-orb"; +import { ModelPicker } from "@/components/channels/composer/model-picker"; import { BusinessComputerLink } from "@/components/edition/team-features-dialog"; import { PluginLogo } from "@/components/plugins/plugin-logo"; import { RoutinesAppHint } from "@/components/routines/routines-app-hint"; @@ -79,6 +80,9 @@ import { failureSaid, loadFailure, } from "@/lib/load-failure"; +import { canChoose } from "@/lib/models/connections"; +import { botDefaultFor, type ModelPick, shownPick } from "@/lib/models/effort"; +import { modelCatalogueQueryOptions } from "@/lib/models/queries"; import { useOrganizationAudience } from "@/lib/organizations/queries"; import { type PluginServer, pluginKeys } from "@/lib/plugins/queries"; import { cn } from "@/lib/utils"; @@ -223,6 +227,12 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { const isolationAllowed = mine?.capabilities.isolatedComputers !== false; /** Shared with the person's own computer unless they tick it. */ const [isolated, setIsolated] = useState(false); + /* + * The Bot's default model, for a Bot that runs here: none until the person picks one, so a Bot + * made without touching it is made as before, on the deployment's default. + */ + const { data: catalogue } = useQuery(modelCatalogueQueryOptions()); + const [defaultPick, setDefaultPick] = useState(); const [step, setStep] = useState("about"); const [direction, setDirection] = useState(1); const [name, setName] = useState(""); @@ -339,6 +349,10 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { // that runs here is made on. None for an agent somebody already runs, since nobody said what // is behind its address. ...(framework ? { harness: framework } : {}), + // Only a Bot that runs here takes OpenBot's model; an agent somebody runs picks its own. + ...(!managed && defaultPick + ? { defaultModel: botDefaultFor(defaultPick, catalogue) } + : {}), }); /* * The ticked apps, given once the Bot exists. A refusal is not a failed create: the Bot is made, @@ -512,6 +526,30 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { }} onVisibility={setVisibility} visibility={visibility} + modelField={ + builtInAvailable && canChoose(catalogue) ? ( + + + Default model + + Optional + + + + + New conversations with this Bot start on this model. + You can change it later in its Setup. + + + ) : null + } /> {!builtInAvailable && (

    @@ -715,7 +753,10 @@ function AboutStep({ onName, onInstructions, onVisibility, + modelField, }: { + /** The Default model field, for a Bot that runs here and has models to choose from. */ + modelField?: ReactNode; name: string; nameError?: string; instructions: string; @@ -772,6 +813,7 @@ function AboutStep({ value={instructions} /> + {modelField} {personal ? ( ) : ( diff --git a/app/src/components/bot-profile/default-model.tsx b/app/src/components/bot-profile/default-model.tsx index f286c60be9..1c52c919cc 100644 --- a/app/src/components/bot-profile/default-model.tsx +++ b/app/src/components/bot-profile/default-model.tsx @@ -31,6 +31,7 @@ import { } from "@/lib/load-failure"; import { connectionOf, pickerGroups } from "@/lib/models/connections"; import { + botDefaultFor, effortLabel, type ModelPick, offeredBotDefault, @@ -104,7 +105,7 @@ export function DefaultModelSection({ await onSave( useDeploymentDefault || !custom ? null - : savedDefault(custom, catalogue), + : botDefaultFor(custom, catalogue), ); setEditing(false); } catch (failure) { @@ -288,26 +289,7 @@ function modelOf( return models?.find(({ id }) => id === pick.model); } -/** - * What a Bot's default is saved as: the model and effort, and with several connections the kind of - * connection it is on (`source`), never one person's connection. With one connection, no source: the - * server stamps the one in use, as it always did. - */ -function savedDefault( - pick: ModelPick, - catalogue: ModelCatalogue | undefined, -): { model: string; effort: string | null; source?: string } { - const source = - pickerGroups(catalogue).length > 0 - ? connectionOf(catalogue, pick.connection)?.source - : undefined; - return { - model: pick.model, - effort: pick.effort, - ...(source ? { source } : {}), - }; -} - +/** How a default reads in its row: the model, and the thinking level where it shows one. */ function modelSummary(model: ModelOption, effort: string | null) { const thinking = shownEffort(model, effort); return thinking ? `${model.label} · ${effortLabel(thinking)}` : model.label; diff --git a/app/src/components/channels/composer/model-picker.tsx b/app/src/components/channels/composer/model-picker.tsx index 51b415dfb4..a4ee8e51ff 100644 --- a/app/src/components/channels/composer/model-picker.tsx +++ b/app/src/components/channels/composer/model-picker.tsx @@ -6,11 +6,12 @@ import { IconCloud, IconCpu, IconCube, + IconPlus, } from "@tabler/icons-react"; import { useMemo, useRef, useState } from "react"; import { HarnessMark } from "@/components/agents/harness-mark"; import { reconnectPath } from "@/components/channels/stopped-connection-notice"; -import { Button } from "@/components/ui/button"; +import { Button, buttonVariants } from "@/components/ui/button"; import { Combobox, ComboboxCollection, @@ -26,7 +27,9 @@ import { TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; +import { useCanConnectProviders } from "@/lib/ai-connection/can-connect"; import { connectionName } from "@/lib/ai-connection/describe"; +import { PROVIDERS_ADDRESS } from "@/lib/ai-connection/paths"; import { providerById, providerRetired } from "@/lib/ai-connection/providers"; import { markFor } from "@/lib/marks"; import { @@ -48,6 +51,9 @@ import type { } from "@/lib/models/queries"; import { cn } from "@/lib/utils"; +/** The plus beside the search, and its tooltip. */ +const CONNECT_MORE = "Connect more providers"; + /** The composer's message box around `inside`, if it is in one. */ function messageBox(inside: HTMLElement | null): HTMLElement | null { return ( @@ -171,10 +177,16 @@ export function ModelPicker({ disabled, saving, stopped = false, + connectMore = true, className, }: { catalogue: ModelCatalogue | undefined; allowSingle?: boolean; + /** + * Whether the popup may offer "Connect more providers" (to whoever can connect one). Off where + * leaving the page would lose work, as in the New Bot sheet. + */ + connectMore?: boolean; defaultModel?: string; /** The settings field displays the value on its trigger. */ showValue?: boolean; @@ -217,6 +229,7 @@ export function ModelPicker({ onChange={onChange} selected={selected} selectedConnection={selected ? on?.id : undefined} + connectMore={connectMore} showValue={showValue} stopped={stopped} /> @@ -237,12 +250,76 @@ export function ModelPicker({ effort={value.model === selected.id ? value.effort : null} onChange={onChange} selected={selected} + connectMore={connectMore} showValue={showValue} stopped={stopped} /> ); } +/** + * The search over the models and, at its right end for whoever can connect another AI, a plus to + * Settings → AI providers. Drawn inside the open popup only, so who may connect is asked when the + * person opens the picker, not by every composer on every page. Two of the popup's grid cells + * rather than a wrapper, since the popup styles its search as its own direct child. + */ +function SearchRow({ + effortsOnly, + modelsColumn, + offerConnect, +}: { + effortsOnly: boolean; + modelsColumn: string; + offerConnect: boolean; +}) { + const canConnect = useCanConnectProviders(offerConnect && !effortsOnly); + const plus = offerConnect && !effortsOnly && canConnect; + return ( + <> + + {plus ? ( + /* + * In the search's own cell, at its right end: not an option, so the arrows never land on + * it, and pressing it doesn't take the focus from the search first. Tab from the search + * reaches it, and the popup stays open. A page of its own, so it leaves the conversation as + * a link does. + */ + + event.preventDefault()} + /> + } + > + + + {CONNECT_MORE} + + ) : null} + + ); +} + /** What the trigger says while several connections have no default and nothing is picked. */ const CHOOSE_A_MODEL = "Choose a model"; @@ -261,9 +338,11 @@ function Picker({ onChange, disabled, stopped, + connectMore, className, }: { catalogue: ModelCatalogue; + connectMore: boolean; /** Several connections, the default first; empty with one, which draws no headings. */ connections: CatalogueConnection[]; /** The default connection's id, whose default model is tagged. */ @@ -583,17 +662,10 @@ function Picker({ })} ) : null} - {noModels && !effortsOnly ? (

    0 + ? connectionOf(catalogue, pick.connection) + : undefined; + const option = (connection?.models ?? catalogue?.models)?.find( + ({ id }) => id === pick.model, + ); + return { + model: pick.model, + effort: pick.effort === option?.defaultEffort ? null : pick.effort, + ...(connection?.source ? { source: connection.source } : {}), + }; +} diff --git a/app/tests/bot-default-for.test.ts b/app/tests/bot-default-for.test.ts new file mode 100644 index 0000000000..941dc36e15 --- /dev/null +++ b/app/tests/bot-default-for.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from "bun:test"; +import { botDefaultFor } from "@/lib/models/effort"; +import type { CatalogueConnection, ModelCatalogue } from "@/lib/models/queries"; + +/* + * A Bot's default as it is saved (createBot and updateBot's defaultModel): the pick's model and + * effort, and, where several AI connections are connected, the kind of connection it is on, so the + * server checks it against that kind and each person runs it on their own connection of it. + */ + +const SOL = { id: "gpt-6.2-sol", label: "GPT-6.2 Sol", vendor: "openai" }; +const OPUS = { + id: "claude-opus-5-5", + label: "Claude Opus 5.5", + vendor: "anthropic", + efforts: ["low", "medium", "high"], + defaultEffort: "medium", +}; + +function connection( + overrides: Partial & + Pick, +): CatalogueConnection { + return { + owner: "personal", + login: "plan", + source: "chatgpt", + isDefault: false, + ready: true, + problem: null, + default: SOL.id, + models: [SOL], + listed: true, + ...overrides, + }; +} + +const ONE: ModelCatalogue = { + provider: "openai", + source: "openai", + exposure: "all", + default: SOL.id, + models: [SOL, OPUS], + choosable: true, +}; + +const TWO: ModelCatalogue = { + ...ONE, + source: "chatgpt", + connections: [ + connection({ id: "openai", provider: "openai", isDefault: true }), + connection({ + id: "anthropic", + provider: "anthropic", + source: "claude", + default: OPUS.id, + models: [OPUS], + }), + ], +}; + +test("with one connection, the default names no kind", () => { + expect(botDefaultFor({ model: OPUS.id, effort: "high" }, ONE)).toEqual({ + model: OPUS.id, + effort: "high", + }); +}); + +test("with several, it names the kind of connection the pick is on", () => { + expect( + botDefaultFor( + { model: OPUS.id, effort: null, connection: "anthropic" }, + TWO, + ), + ).toEqual({ model: OPUS.id, effort: null, source: "claude" }); + // No connection named: the default one's. + expect(botDefaultFor({ model: SOL.id, effort: null }, TWO)).toEqual({ + model: SOL.id, + effort: null, + source: "chatgpt", + }); +}); + +test("the model's own default thinking level is saved as no level, as a conversation's is", () => { + // So the Bot follows the model's default, and the Setup page shows Default rather than Medium. + expect(botDefaultFor({ model: OPUS.id, effort: "medium" }, ONE)).toEqual({ + model: OPUS.id, + effort: null, + }); + expect( + botDefaultFor( + { model: OPUS.id, effort: "medium", connection: "anthropic" }, + TWO, + ), + ).toEqual({ model: OPUS.id, effort: null, source: "claude" }); +}); diff --git a/app/tests/can-connect-providers.test.tsx b/app/tests/can-connect-providers.test.tsx new file mode 100644 index 0000000000..87cffa3bc5 --- /dev/null +++ b/app/tests/can-connect-providers.test.tsx @@ -0,0 +1,89 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, renderHook, waitFor } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { useCanConnectProviders } from "@/lib/ai-connection/can-connect"; +import { queryClient } from "@/query-client"; +import { settleReactWork } from "./settle-react-work"; + +/* + * Whether this person can connect an AI provider themselves: on OpenBot Cloud everybody brings + * their own; elsewhere only where the organization's connection is theirs to change, or inside + * OpenBot Desktop. What decides whether "Connect more providers" is offered, and whether Settings → + * AI providers has anything to show rather than "Set by your organization". + */ + +const ORG = "/api/v2/organizations/default"; +const originalFetch = globalThis.fetch; +let personal: unknown = null; +let organization: unknown = null; +let hold: Promise | undefined; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); + globalThis.fetch = Object.assign( + async (input: string | URL | Request) => { + const path = new URL(String(input), "http://localhost/").pathname; + await hold; + const answer = + path === `${ORG}/people/me/ai-connection` + ? personal + : path === `${ORG}/ai-connection` + ? organization + : null; + return answer === null + ? Response.json({ error: "not served" }, { status: 404 }) + : Response.json(answer); + }, + { preconnect: originalFetch.preconnect }, + ); +}); +afterEach(() => { + cleanup(); + queryClient.clear(); + personal = null; + organization = null; + hold = undefined; +}); +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +const wrapper = ({ children }: { children: ReactNode }) => ( + {children} +); + +/** The hook's answer once both reads have settled. */ +async function settled() { + const view = renderHook(() => useCanConnectProviders(), { wrapper }); + await waitFor(() => + expect(queryClient.isFetching({ queryKey: ["ai-connection"] })).toBe(0), + ); + return view.result.current; +} + +test("on OpenBot Cloud everybody can connect their own", async () => { + personal = { available: true, required: false, uses: "organization" }; + expect(await settled()).toBe(true); +}); + +test("where the organization's AI is theirs to change, they can", async () => { + organization = { editable: true }; + expect(await settled()).toBe(true); +}); + +test("a member whose admin set the AI, in a plain browser, can't", async () => { + personal = { available: false, required: false, uses: "organization" }; + organization = { editable: false }; + expect(await settled()).toBe(false); +}); + +test("while either answer is on its way, nothing is offered", () => { + hold = new Promise(() => {}); + personal = { available: true, required: false, uses: "organization" }; + const view = renderHook(() => useCanConnectProviders(), { wrapper }); + expect(view.result.current).toBe(false); +}); diff --git a/app/tests/model-picker.test.tsx b/app/tests/model-picker.test.tsx index 70e90ed5a2..e12860b39f 100644 --- a/app/tests/model-picker.test.tsx +++ b/app/tests/model-picker.test.tsx @@ -83,6 +83,10 @@ let saved: Record = {}; let writes: ({ channelId: string } & ConversationModel)[] = []; /** What the server offers now: an admin narrowing the allowlist changes it under an open tab. */ let offered: ModelCatalogue = catalogue; +/** Whether this person may connect an AI provider themselves (OpenBot Cloud's own AI). */ +let mayConnect = false; +/** Every read of who may connect a provider, the person's own and the organization's. */ +let connectionReads: string[] = []; beforeAll(() => { GlobalRegistrator.register({ url: "http://localhost/" }); @@ -91,6 +95,16 @@ beforeAll(() => { const url = new URL(String(input), "http://localhost/"); if (catalogueView(url) === "offered") return Response.json(catalogueBody(offered)); + if (url.pathname.endsWith("/ai-connection")) + connectionReads.push(url.pathname); + if (url.pathname.endsWith("/people/me/ai-connection")) + return mayConnect + ? Response.json({ + available: true, + required: false, + uses: "organization", + }) + : Response.json({ error: "not served" }, { status: 404 }); const channelId = modelChoiceConversation(url.pathname); if (!channelId) return Response.json({ error: "not served" }, { status: 404 }); @@ -135,6 +149,8 @@ afterEach(() => { writes = []; pendingWrite = undefined; offered = catalogue; + mayConnect = false; + connectionReads = []; }); afterAll(async () => { await settleReactWork(); @@ -829,3 +845,58 @@ test("picking a model that takes no effort closes the popup", async () => { await waitFor(() => expect(writes).toHaveLength(1)); await waitFor(() => expect(view.queryByRole("dialog")).toBeNull()); }); + +test("someone who can connect a provider gets Connect more providers beside the search, to Settings → AI providers", async () => { + mayConnect = true; + const { popup } = await openPicker(/GPT-5\.5/); + const link = await within(popup).findByRole("link", { + name: "Connect more providers", + }); + expect(link.getAttribute("href")).toBe("/settings/providers"); +}); + +test("someone who can't connect one sees no plus", async () => { + const { popup } = await openPicker(/GPT-5\.5/); + await waitFor(() => + expect(queryClient.isFetching({ queryKey: ["ai-connection"] })).toBe(0), + ); + expect( + within(popup).queryByRole("link", { name: "Connect more providers" }), + ).toBeNull(); +}); + +test("on its efforts alone the picker shows no plus, and the arrows never land on it", async () => { + mayConnect = true; + const { popup, user, view } = await openPicker(/GPT-5\.5/); + await within(popup).findByRole("link", { name: "Connect more providers" }); + // From the search, an arrow moves among the models, never onto the plus. + await user.keyboard("{ArrowDown}"); + const highlighted = popup.querySelector("[data-highlighted]"); + expect(highlighted?.getAttribute("role")).toBe("option"); + expect(document.activeElement?.getAttribute("placeholder")).toBe( + "Search models", + ); + // On a model that thinks, the popup is its efforts alone, and has no plus. + await user.click(within(popup).getByRole("option", { name: "GPT-6 Sol" })); + await waitFor(() => expect(writes).toHaveLength(1)); + const open = view.getByRole("dialog"); + expect(within(open).queryByRole("group", { name: "Models" })).toBeNull(); + expect( + within(open).queryByRole("link", { name: "Connect more providers" }), + ).toBeNull(); +}); + +test("a closed picker asks nothing about connecting providers; opening it does", async () => { + mayConnect = true; + const view = render(, { wrapper }); + const trigger = await view.findByRole("combobox", { name: /GPT-5\.5/ }); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + expect(connectionReads).toEqual([]); + const user = userEvent.setup({ document }); + await user.click(trigger); + const popup = await view.findByRole("dialog"); + await within(popup).findByRole("link", { name: "Connect more providers" }); + expect(connectionReads.length).toBeGreaterThan(0); +}); diff --git a/app/tests/new-bot-sheet.test.tsx b/app/tests/new-bot-sheet.test.tsx index eea4577ce2..d5dbb37996 100644 --- a/app/tests/new-bot-sheet.test.tsx +++ b/app/tests/new-bot-sheet.test.tsx @@ -33,6 +33,8 @@ import { ISOLATION_UNAVAILABLE, } from "@/lib/agents/isolation"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; +import type { ModelCatalogue } from "@/lib/models/queries"; +import { queryClient as appQueryClient } from "@/query-client"; import { DEPLOYMENT_PATH, deploymentResponse, @@ -51,6 +53,7 @@ import { sentRequest, TEST_CONNECTION_PATH, } from "./bots-api"; +import { catalogueBody, catalogueView } from "./models-api"; import { settleReactWork } from "./settle-react-work"; /* @@ -112,9 +115,34 @@ let servers: TodayServer[] = []; let requested: string[] = []; /** A create the server refuses with this sentence, as it refuses an address it couldn't reach. */ let createRefusal: string | undefined; +/** The models this person may pick, or none when the catalogue isn't served. */ +let models: ModelCatalogue | undefined; +/** Whether this person may connect an AI provider themselves (OpenBot Cloud's own AI). */ +let mayConnect = false; + +const CATALOGUE: ModelCatalogue = { + provider: "openai", + source: "openai", + exposure: "all", + default: "gpt-5.5", + choosable: true, + models: [ + { + id: "gpt-6.1-terra", + label: "GPT-6.1 Terra", + vendor: "openai", + efforts: ["low", "medium", "high"], + defaultEffort: "medium", + }, + { id: "gpt-5.5", label: "GPT-5.5", vendor: "openai" }, + ], +}; beforeEach(() => { createRefusal = undefined; + models = undefined; + mayConnect = false; + appQueryClient.clear(); builtInAvailable = true; isolationAvailable = true; mayIsolate = true; @@ -130,6 +158,17 @@ beforeEach(() => { async (path: Parameters[0], init?: RequestInit) => { const body = init?.body ? JSON.parse(String(init.body)) : undefined; requested.push(String(path)); + if ( + models && + catalogueView(new URL(String(path), "http://localhost/")) === "offered" + ) + return Response.json(catalogueBody(models)); + if (mayConnect && String(path).endsWith("/people/me/ai-connection")) + return Response.json({ + available: true, + required: false, + uses: "organization", + }); if (path === DEPLOYMENT_PATH) { return deploymentResponse({ edition, @@ -838,3 +877,106 @@ test("every setup the hint links is a section of the frameworks guide", async () expect(anchors.has(anchor ?? "")).toBe(true); } }); + +/** The Default model field's picker, by its label. */ +async function defaultModelPicker(view: ReturnType) { + const field = (await view.findByText("Default model")).closest( + '[data-slot="field"]', + ) as HTMLElement; + return within(field).getByRole("combobox"); +} + +/** The picker's popup: the second dialog, over the sheet's own. */ +async function pickerPopup(view: ReturnType) { + await waitFor(() => expect(view.getAllByRole("dialog")).toHaveLength(2)); + return view.getAllByRole("dialog")[1] as HTMLElement; +} + +/** Back to the sheet alone, once the picker's popup has closed. */ +async function pickerClosed(view: ReturnType) { + await waitFor(() => expect(view.getAllByRole("dialog")).toHaveLength(1)); +} + +test("a default model picked on New Bot is sent with the create", async () => { + models = CATALOGUE; + const { view, user } = await opened(); + await user.type(view.getByLabelText("Name"), "Designer"); + await user.click(await defaultModelPicker(view)); + const popup = await pickerPopup(view); + await user.click( + within(popup).getByRole("option", { name: "GPT-6.1 Terra" }), + ); + await user.click( + within(await pickerPopup(view)).getByRole("option", { + name: "High", + }), + ); + await pickerClosed(view); + await user.click(view.getByRole("button", { name: "Create Bot" })); + await waitFor(() => expect(creates).toHaveLength(1)); + expect(creates[0]?.defaultModel).toEqual({ + model: "gpt-6.1-terra", + effort: "high", + }); +}); + +test("left alone, the Default model field sends nothing", async () => { + models = CATALOGUE; + const { view, user } = await opened(); + await defaultModelPicker(view); + await user.type(view.getByLabelText("Name"), "Designer"); + await user.click(view.getByRole("button", { name: "Create Bot" })); + await waitFor(() => expect(creates).toHaveLength(1)); + expect(Object.hasOwn(creates[0] ?? {}, "defaultModel")).toBe(false); +}); + +test("nothing to choose, no Default model field", async () => { + models = { ...CATALOGUE, choosable: false }; + const { view } = await opened(); + await waitFor(() => + expect(requested.some((path) => path.includes("/model-catalogue"))).toBe( + true, + ), + ); + await settle(); + expect(view.queryByText("Default model")).toBeNull(); +}); + +test("connecting your own agent never sends a default model", async () => { + models = CATALOGUE; + const { view, user } = await opened(); + await user.click(await defaultModelPicker(view)); + await user.click( + within(await pickerPopup(view)).getByRole("option", { + name: /^GPT-5\.5/, + }), + ); + await pickerClosed(view); + await user.type(view.getByLabelText("Name"), "Expense Review"); + await user.click(view.getByRole("button", { name: /^Bring your own agent/ })); + await user.click(view.getByRole("button", { name: /^LangChain/ })); + await user.type( + await view.findByLabelText("Agent address"), + "https://agent.example.com/ag-ui", + ); + await user.click(view.getByRole("button", { name: "Create Bot" })); + await waitFor(() => expect(creates).toHaveLength(1)); + expect(Object.hasOwn(creates[0] ?? {}, "defaultModel")).toBe(false); +}); + +test("the Default model field offers no Connect more providers, so the half-made Bot is never left behind", async () => { + models = CATALOGUE; + mayConnect = true; + const { view, user } = await opened(); + await user.type(view.getByLabelText("Name"), "Designer"); + await user.click(await defaultModelPicker(view)); + const popup = await pickerPopup(view); + await settle(); + expect( + within(popup).queryByRole("link", { name: "Connect more providers" }), + ).toBeNull(); + // Nor does it ask who may connect one. + expect( + requested.some((path) => path.endsWith("/people/me/ai-connection")), + ).toBe(false); +}); diff --git a/mobile/src/api/generated/model/botFieldsDefaultModel.ts b/mobile/src/api/generated/model/botDefaultModelInput.ts similarity index 78% rename from mobile/src/api/generated/model/botFieldsDefaultModel.ts rename to mobile/src/api/generated/model/botDefaultModelInput.ts index 1007ad28ed..96c399d90a 100644 --- a/mobile/src/api/generated/model/botFieldsDefaultModel.ts +++ b/mobile/src/api/generated/model/botDefaultModelInput.ts @@ -3,10 +3,10 @@ */ /** - * A model from the connected provider and its thinking level. Null resets to the deployment default. Omit to keep the current setting. + * A model from the connected provider, as the model catalogue names it, and its thinking level. * @nullable */ -export type BotFieldsDefaultModel = { +export type BotDefaultModelInput = { /** * @minLength 1 * @maxLength 500 diff --git a/mobile/src/api/generated/model/botFields.ts b/mobile/src/api/generated/model/botFields.ts index c0f7ac4c99..c5fcbb653c 100644 --- a/mobile/src/api/generated/model/botFields.ts +++ b/mobile/src/api/generated/model/botFields.ts @@ -2,8 +2,8 @@ * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ import type { BotComputer } from "./botComputer"; +import type { BotDefaultModelInput } from "./botDefaultModelInput"; import type { BotEndpoint } from "./botEndpoint"; -import type { BotFieldsDefaultModel } from "./botFieldsDefaultModel"; import type { BotInstructions } from "./botInstructions"; import type { BotIsolated } from "./botIsolated"; import type { BotKey } from "./botKey"; @@ -22,9 +22,6 @@ export interface BotFields { isolated?: BotIsolated; computer?: BotComputer; instructions?: BotInstructions; - /** - * A model from the connected provider and its thinking level. Null resets to the deployment default. Omit to keep the current setting. - * @nullable - */ - defaultModel?: BotFieldsDefaultModel; + /** A model from the connected provider and its thinking level. Null resets to the deployment default. Omit to keep the current setting. */ + defaultModel?: BotDefaultModelInput | null; } diff --git a/mobile/src/api/generated/model/createBotRequest.ts b/mobile/src/api/generated/model/createBotRequest.ts index b920d35c29..423fadb29f 100644 --- a/mobile/src/api/generated/model/createBotRequest.ts +++ b/mobile/src/api/generated/model/createBotRequest.ts @@ -1,6 +1,7 @@ /** * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. */ +import type { BotDefaultModelInput } from "./botDefaultModelInput"; import type { BotEndpoint } from "./botEndpoint"; import type { BotInstructions } from "./botInstructions"; import type { BotIsolated } from "./botIsolated"; @@ -23,6 +24,8 @@ export interface CreateBotRequest { auth?: BotKey; isolated?: BotIsolated; instructions?: BotInstructions; + /** The Bot's default model and thinking level, checked as updateBot checks it. Omit, or send null, for the deployment default. */ + defaultModel?: BotDefaultModelInput | null; /** The framework an agent somebody runs themselves is built on, by its id in OpenBot's harness list (shared/harnesses.json), which the server checks every create against. Empty means none was named, as for an agent somebody already runs. "byo-url" is not one: it names no framework. Kept only with an endpoint, with one exception: "langgraph-ts" sent with no endpoint asks for a Bot that runs inside OpenBot on OpenBot's own LangGraph (TypeScript) engine, which is what the New Bot sheet sends. The deployment decides what each run uses: a Claude plan keeps the Claude Agent SDK engine, a ChatGPT plan signed in on OpenBot Desktop the OpenAI Agents SDK engine, and an administrator may switch new Bots back to the built-in agent. */ harness?: CreateBotRequestHarness; } diff --git a/mobile/src/api/generated/model/index.ts b/mobile/src/api/generated/model/index.ts index ef77176699..00cb2bd0ba 100644 --- a/mobile/src/api/generated/model/index.ts +++ b/mobile/src/api/generated/model/index.ts @@ -116,9 +116,9 @@ export * from "./botConnectionTestRequest"; export * from "./botConnectionTestRequestHeaders"; export * from "./botDeclineReport"; export * from "./botDefaultModel"; +export * from "./botDefaultModelInput"; export * from "./botEndpoint"; export * from "./botFields"; -export * from "./botFieldsDefaultModel"; export * from "./botForbiddenResponse"; export * from "./botGrant"; export * from "./botGrantAction"; From c418359f493094ac52ca02d1b37b568f5c7b9bed Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 15:30:26 -0800 Subject: [PATCH 012/224] Back off and stay quiet when the server says too many requests (#2515) * Back off and stay quiet when the server says too many requests The server now answers 429 with a sentence and Retry-After when one person asks too much of it at once. The app read that as a failure: every refused read drew "Couldn't load" in red, and a polling read asked again on its own interval however often it was refused, which kept the person over the limit. Web app: - A read refused 429 is retried quietly by the query client: one with something to show keeps it, one loading for the first time keeps loading. Each try waits the Retry-After, doubled for each refusal in a row, up to a minute, with a little spread. A polling read's interval waits the same way and goes back to normal once answered. A first load still refused after 30 seconds fails with the 429, which every screen draws as the calm sentence, and is asked again after each wait. - A write refused 429 says the server's sentence, drawn calmly, and is not sent again by itself. - A run the runtime refused 429 says the server's sentence calmly, as a 503 hold is said, instead of reading as a rule that refused the person for good. - Learning's review keeps its "may be out of date" line while its read is retried. Desktop: - A 429 on a token refresh no longer ends the sign-in; the refresh waits for Retry-After. - A 429 to the folder-access poll or hand-back no longer ends approved folders, and the next poll waits for Retry-After. - Connecting to an OpenBot over its limit says it is busy, never that there is no OpenBot there. - The local status watcher reads a 429 as an answer and waits Retry-After before asking again. * Wait for the page to be still, not a fixed time, in the chat's 429 browser test --- .../components/settings/learning-review.tsx | 11 +- app/src/lib/copilot/stopped-turn.ts | 79 +++++- app/src/lib/load-failure.tsx | 34 ++- app/src/query-client.ts | 158 +++++++++-- app/tests/learning-review.test.tsx | 3 +- .../organization-unavailable-chat.test.tsx | 109 +++++++- app/tests/too-many-requests-rules.test.ts | 71 +++++ app/tests/too-many-requests.test.tsx | 247 ++++++++++++++++++ desktop/src-tauri/src/connected/address.rs | 46 +++- .../src/connected/fake_openbot_tests.rs | 48 +++- desktop/src-tauri/src/connected/mod.rs | 9 + desktop/src-tauri/src/connected/relay.rs | 159 ++++++++++- desktop/src-tauri/src/connected/sign_in.rs | 73 +++++- desktop/src-tauri/src/desktop_connection.rs | 70 ++++- desktop/src-tauri/src/host_access.rs | 184 +++++++++++-- desktop/src-tauri/src/lib.rs | 1 + desktop/src-tauri/src/main.rs | 19 +- desktop/src-tauri/src/rate_limited.rs | 71 +++++ 18 files changed, 1312 insertions(+), 80 deletions(-) create mode 100644 app/tests/too-many-requests-rules.test.ts create mode 100644 app/tests/too-many-requests.test.tsx create mode 100644 desktop/src-tauri/src/rate_limited.rs diff --git a/app/src/components/settings/learning-review.tsx b/app/src/components/settings/learning-review.tsx index 2691424dea..2e2449e9e3 100644 --- a/app/src/components/settings/learning-review.tsx +++ b/app/src/components/settings/learning-review.tsx @@ -37,6 +37,7 @@ import { failureOf, failureSaid, isHeld, + tooManyRequests, } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; @@ -201,7 +202,15 @@ export function LearningReview({

    ); } - const stale = review.error ? staleSentence(review.error) : null; + /* + * A 429 is retried quietly while the last review stays on screen (query-client.ts), so it is the + * retry's reason, not an error, that says the review may be out of date meanwhile. + */ + const stale = review.error + ? staleSentence(review.error) + : tooManyRequests(review.failureReason) + ? staleSentence(review.failureReason) + : null; const { canReview, spaces: sources, autoApprove } = review.data; // Shown at once while the save is on its way, as a switch is. const autoApproveOn = diff --git a/app/src/lib/copilot/stopped-turn.ts b/app/src/lib/copilot/stopped-turn.ts index 67cadc9bfb..7872d5e6fd 100644 --- a/app/src/lib/copilot/stopped-turn.ts +++ b/app/src/lib/copilot/stopped-turn.ts @@ -4,7 +4,13 @@ import { botNoLongerUsable } from "@/lib/agents/queries"; import { startedRunId } from "@/lib/copilot/quiet-run"; import { problemRequestId, recordProblem } from "@/lib/desktop/problems"; import { useClearWhenHoldEnds } from "@/lib/held-ends"; -import { type Failure, isHeld } from "@/lib/load-failure"; +import { ClientError } from "@/lib/client"; +import { + BUSY, + type Failure, + isHeld, + TOO_MANY_REQUESTS, +} from "@/lib/load-failure"; import { isPlanRequired, showCardNeeded } from "@/lib/plan/card-needed"; /** @@ -36,6 +42,8 @@ export function stoppedReason(reported: unknown): string { ? reported : ""; notePlanRefusal(reported, said); + const busy = tooManyRuns(reported); + if (busy) return busy.message; const refused = refusalForPerson(said); if (refused) return refused; const unreachable = backEndUnreachable(said); @@ -136,7 +144,8 @@ export function laterRunFailure(reported: unknown): string | null { : typeof reported === "string" ? reported : ""; - if (refusalForPerson(said)) return stoppedReason(reported); + if (refusalForPerson(said) || tooManyRuns(reported)) + return stoppedReason(reported); if ( REST_REQUEST_FAILED.test(said.trim()) || /failed to fetch|load failed|networkerror|network connection/i.test(said) @@ -223,12 +232,66 @@ function refusalForPerson(said: string): string | null { typeof status === "number" && status >= 400 && status < 500 && + // Too many requests is not a rule: sent again later, the run goes (`tooManyRuns`). + status !== TOO_MANY_REQUESTS && typeof detail === "string" && detail.trim() ? detail.trim() : null; } +/** How AG-UI's HTTP agent words a refused request: `HTTP : `, the status kept beside it. */ +const HTTP_REFUSED = /^HTTP (\d{3}):\s*/; + +/** + * A run the runtime refused because the person asked too much of OpenBot at once (429), as the + * refusal the app's own client would have made of it: its server's sentence ({@link BUSY} when it + * sent none), so it is drawn calmly, as a 503 hold is (lib/load-failure.tsx). Undefined otherwise. + * + * Through Intelligence the client throws the problem as `REST run request failed: `; over + * the plain event stream, AG-UI's HTTP agent throws `HTTP 429: ` with the status kept. The + * body was read as the person's own refusal before (`refusalForPerson`), so it was said in red under + * the message, for good, as if sending it again could never work. + */ +export function tooManyRuns(reported: unknown): ClientError | undefined { + const said = + reported instanceof Error + ? reported.message + : typeof reported === "string" + ? reported + : ""; + const status = + reported instanceof Error + ? (reported as Error & { status?: unknown }).status + : undefined; + const http = HTTP_REFUSED.exec(said.trim()); + let body = refusedBody(said); + if (body === null && http) { + try { + body = JSON.parse(said.trim().slice(http[0].length)); + } catch { + body = null; + } + } + const problem = + body && typeof body === "object" ? (body as Record) : null; + const refused = + problem?.status === TOO_MANY_REQUESTS || + status === TOO_MANY_REQUESTS || + http?.[1] === String(TOO_MANY_REQUESTS); + if (!refused) return undefined; + const detail = + typeof problem?.detail === "string" && problem.detail.trim() + ? problem.detail.trim() + : undefined; + return new ClientError( + detail ?? BUSY, + TOO_MANY_REQUESTS, + typeof problem?.code === "string" ? problem.code : undefined, + problem ?? undefined, + ); +} + function backEndUnreachable(said: string): string | null { const match = REST_REQUEST_FAILED.exec(said.trim()); if (!match) return null; @@ -263,8 +326,11 @@ function refusedRequest(reported: unknown): "run" | "connect" | null { reported instanceof Error ? (reported as Error & { status?: unknown }).status : undefined; - // 503: OpenBot may be holding off, which only the server can say (see `askAboutBot`). - return status === 404 || status === 503 ? "run" : null; + // 503: OpenBot may be holding off, which only the server can say (see `askAboutBot`). 429: too many + // requests for now, said calmly (`tooManyRuns`). + return status === 404 || status === 503 || status === TOO_MANY_REQUESTS + ? "run" + : null; } /** What a person reads when the Bot they were talking to is not one they can use any more. */ @@ -294,6 +360,9 @@ export async function failedRunReason( botId: string, noLongerUsable: (botId: string) => Promise = botNoLongerUsable, ): Promise { + // Too many requests for now: the server already said so, and asking it about the Bot is one more. + const busy = tooManyRuns(reported); + if (busy) return busy; const said = { message: stoppedReason(reported) }; const request = refusedRequest(reported); if (!request) return said; @@ -318,6 +387,8 @@ export async function laterRunReason( noLongerUsable: (botId: string) => Promise = botNoLongerUsable, ): Promise { if (!requestNotMade(reported)) return { message: said }; + const busy = tooManyRuns(reported); + if (busy) return busy; const asked = await askAboutBot(botId, noLongerUsable); return asked.held ?? { message: said }; } diff --git a/app/src/lib/load-failure.tsx b/app/src/lib/load-failure.tsx index a4ed6648cc..6414873348 100644 --- a/app/src/lib/load-failure.tsx +++ b/app/src/lib/load-failure.tsx @@ -20,19 +20,46 @@ * move or a brief outage is neither: it is temporary, and OpenBot is already waiting it out. So the * server's sentence comes back as muted text (`data-held`), which wins over the red of the line the * screen drew it in. The screen's own sentence keeps the screen's own look. + * + * TOO MANY REQUESTS IS THE SAME KIND OF ANSWER. The server limits how much one person, key or + * organization asks of it at once, and over the limit answers 429 with a sentence and `Retry-After`. + * Nothing broke: the request is to be made again a little later. A read refused 429 is asked again by + * itself, quietly, and keeps what it showed (query-client.ts). Should a screen still have to say + * something, or a press be refused, it is this calm sentence, never "Couldn't load" in red. */ import type { ReactNode } from "react"; import { ClientError } from "@/lib/client"; import { cn } from "@/lib/utils"; +/** The status the server answers with when it is asked more than it takes from one person at once. */ +export const TOO_MANY_REQUESTS = 429; + +/** + * What a person reads for a 429 that came without a sentence of its own (a proxy's). The server's own + * sentence is said when it sent one. + */ +export const BUSY = "OpenBot is busy right now. Try again in a moment."; + +/** How long a 429 that didn't say (`Retry-After`) is waited out before asking again. */ +const BUSY_WAIT_MS = 5_000; +/** The soonest anything refused 429 is asked again, whatever `Retry-After` said: never back to back. */ +const BUSY_SOONEST_MS = 1_000; + +/** Whether `error` is the server saying it has been asked too much for now (429). */ +export function tooManyRequests(error: unknown): error is ClientError { + return error instanceof ClientError && error.status === TOO_MANY_REQUESTS; +} + /** - * The server's own sentence when `error` is a 503 that carries one and a `Retry-After`. + * The server's own sentence when `error` is a 503 that carries one and a `Retry-After`, or a 429 + * (its sentence, or {@link BUSY} when it sent none). * * Or, when `error` was thrown because of one (its `cause`), the error's own longer sentence that * folds it in: "It's saved on the Routines page, but it didn't start. OpenBot is moving this * organization. Try again in a moment." is still OpenBot holding off, so it is drawn calmly too. */ export function unavailableSaid(error: unknown): string | undefined { + if (tooManyRequests(error)) return error.said ?? BUSY; if ( error instanceof ClientError && error.status === 503 && @@ -191,9 +218,12 @@ export function loadFailureText( /** * How long to wait before asking again, when the refusal is a 503 that said (`Retry-After`): the * read is then asked again by itself after that long, each time it is refused, and not retried at - * once before. + * once before. A 429 always says to wait: its `Retry-After`, a second at the soonest, or a few + * seconds when it didn't say (a refused run, whose headers the runtime's client drops). */ export function askAgainAfterMs(error: unknown): number | undefined { + if (tooManyRequests(error)) + return Math.max(error.retryAfterMs ?? BUSY_WAIT_MS, BUSY_SOONEST_MS); return error instanceof ClientError && error.status === 503 ? error.retryAfterMs : undefined; diff --git a/app/src/query-client.ts b/app/src/query-client.ts index 9ff689ecdc..385af55b96 100644 --- a/app/src/query-client.ts +++ b/app/src/query-client.ts @@ -24,7 +24,7 @@ import { holdReadsWhileConnectionLost, retryWhileConnectionLost, } from "@/lib/desktop/connection-lost"; -import { askAgainAfterMs } from "@/lib/load-failure"; +import { askAgainAfterMs, tooManyRequests } from "@/lib/load-failure"; import { currentOrganizationId, onOrganizationChange, @@ -88,6 +88,76 @@ focusManager.setEventListener((handleFocus) => { }; }); +/** Any read in the cache, as its events hand it over. */ +type AnyQuery = Query; + +/** + * The soonest a held read is asked again, whatever Retry-After said: never in a tight loop. The page + * standing in for a held app waits it too (components/layout/unavailable-page.tsx). + */ +export const SOONEST_ASK_AGAIN_MS = 1_000; +/** The longest a held read waits before it is asked again, whatever Retry-After said. */ +const LONGEST_ASK_AGAIN_MS = 60_000; + +/** + * How long a read with nothing to show yet is asked again quietly after its first 429, before the + * screen may say, calmly, that OpenBot is busy. A read that has something to show keeps showing it, + * and is asked again quietly for as long as it is refused. + */ +export const QUIET_WHILE_BUSY_MS = 30_000; + +/** One read's run of 429s since it was last answered: when it began, how many, and the wait after the last. */ +type Refusals = { since: number; times: number; waitMs: number }; + +/** Each read refused 429 since it was last answered. Dropped when it is answered. */ +const refusedAsTooMany = new WeakMap(); +/** The 429s already counted, so one refusal is counted once wherever it is seen first. */ +const counted = new WeakSet(); + +/** + * The wait after the `times`th 429 in a row: the Retry-After it gave (a second at the soonest), doubled + * for each refusal after the first, a minute at the most. Up to a tenth more is added at random, so the + * many reads one page makes, refused together, are not all asked again in the same moment. Never less + * than Retry-After: the server is never asked before the time it gave. + */ +export function busyWaitMs( + retryAfterMs: number | undefined, + times: number, + spread: number = Math.random(), +): number { + const said = Math.max( + retryAfterMs ?? SOONEST_ASK_AGAIN_MS, + SOONEST_ASK_AGAIN_MS, + ); + const grown = Math.min( + said * 2 ** Math.max(times - 1, 0), + LONGEST_ASK_AGAIN_MS, + ); + return Math.min(Math.round(grown * (1 + spread / 10)), LONGEST_ASK_AGAIN_MS); +} + +/** Counts `error`, a 429 `query` was answered with, once, and gives the read's run of refusals. */ +function refusedTooMany(query: AnyQuery, error: unknown): Refusals { + const before = refusedAsTooMany.get(query); + if ( + before && + (typeof error !== "object" || error === null || counted.has(error)) + ) + return before; + if (typeof error === "object" && error !== null) counted.add(error); + const times = (before?.times ?? 0) + 1; + const refusals = { + since: before?.since ?? Date.now(), + times, + waitMs: busyWaitMs( + tooManyRequests(error) ? error.retryAfterMs : undefined, + times, + ), + }; + refusedAsTooMany.set(query, refusals); + return refusals; +} + /** * The app's client. Every query's retry rule is its own, wrapped once here so that a read failing * while OpenBot Desktop can't reach the OpenBot it is connected to waits for it instead of failing @@ -104,6 +174,18 @@ focusManager.setEventListener((handleFocus) => { * the last try (TanStack Query hands it over as `failureReason`, not `error`), and the screen would * say nothing about the hold while it waits. Said here rather than in one query's options, where it * would replace the retry rule this client was given. + * + * A 429 (too many requests from this person for now) is the opposite case: nothing is said about it. + * Before this, a read refused 429 drew its "Couldn't load" in red, and a polling read asked again on + * its own interval, however often it was refused, which kept the person over the limit. Now it is + * retried through `retry` and `retryDelay`, which keeps the refusal to itself (`failureReason`): a + * read with something to show keeps showing it, and one loading for the first time keeps loading. Each + * try waits the Retry-After the last refusal gave, doubled for each refusal in a row, up to a minute + * (`busyWaitMs`). TanStack Query asks nothing else of a read while its retry waits, so a polling read's + * own interval waits too, and the interval is lengthened the same way while the read is refused + * (`refetchInterval` below). Once answered, it polls as before. A read with nothing to show that is + * still refused after {@link QUIET_WHILE_BUSY_MS} fails with the 429, which screens draw as the calm + * sentence (lib/load-failure.tsx), and is asked again after each wait until it is answered. */ class OpenBotQueryClient extends QueryClient { override defaultQueryOptions< @@ -147,11 +229,29 @@ class OpenBotQueryClient extends QueryClient { >; const resolved = super.defaultQueryOptions(options); const retry = resolved.retry ?? false; + const retryDelay = resolved.retryDelay; + const interval = resolved.refetchInterval; + // The read these options are for, looked up when it is refused: the cache makes it after this. + const cache = this.getQueryCache(); + const queryHash = resolved.queryHash; + const read = (): AnyQuery | undefined => + queryHash === undefined + ? undefined + : (cache.get(queryHash) as AnyQuery | undefined); return { ...resolved, ...retryWhileConnectionLost( this, (failureCount, error) => { + if (tooManyRequests(error)) { + const query = read(); + if (!query) return false; + const { since } = refusedTooMany(query, error); + return ( + query.state.data !== undefined || + Date.now() - since < QUIET_WHILE_BUSY_MS + ); + } if ( inNoOrganization(error) || heldOutBySso(error) || @@ -164,8 +264,38 @@ class OpenBotQueryClient extends QueryClient { if (typeof retry === "number") return failureCount < retry; return retry; }, - resolved.retryDelay, + (failureCount, error) => { + if (tooManyRequests(error)) { + const query = read(); + return query + ? refusedTooMany(query, error).waitMs + : busyWaitMs(error.retryAfterMs, 1); + } + if (typeof retryDelay === "function") + return retryDelay(failureCount, error); + if (typeof retryDelay === "number") return retryDelay; + // Query's own default. + return Math.min(1000 * 2 ** failureCount, 30_000); + }, ), + ...(interval === undefined || interval === false + ? {} + : { + refetchInterval: ( + query: Query, + ) => { + const every = + typeof interval === "function" ? interval(query) : interval; + const refused = refusedAsTooMany.get( + query as unknown as AnyQuery, + ); + return refused === undefined || + every === undefined || + every === false + ? every + : Math.max(every, refused.waitMs); + }, + }), }; } } @@ -187,20 +317,9 @@ function showBeingDeletedWhenRefusedForIt(error: unknown): void { if (beingDeletedRefusal(error)) showBeingDeleted(); } -/** Any read in the cache, as its events hand it over. */ -type AnyQuery = Query; - -/** The reads waiting to be asked again after a 503's Retry-After: one wait each, never two. */ +/** The reads waiting to be asked again after a 503's or a 429's Retry-After: one wait each, never two. */ const askingAgain = new WeakSet(); -/** - * The soonest a held read is asked again, whatever Retry-After said: never in a tight loop. The page - * standing in for a held app waits it too (components/layout/unavailable-page.tsx). - */ -export const SOONEST_ASK_AGAIN_MS = 1_000; -/** The longest a held read waits before it is asked again, whatever Retry-After said. */ -const LONGEST_ASK_AGAIN_MS = 60_000; - /** * A read refused 503 with a Retry-After (an organization being moved, or its database out of reach, * `lib/load-failure.tsx`): asked again by itself after that long, and again after each refusal for as @@ -213,9 +332,14 @@ const LONGEST_ASK_AGAIN_MS = 60_000; * * One read, one wait: a read refused again while its wait runs (a second screen asking for it) * waits the same wait, and the server is asked about it once per Retry-After at most. + * + * A read that failed with a 429 (refused for longer than {@link QUIET_WHILE_BUSY_MS} with nothing to + * show) waits its run of refusals' wait, which grows with each one (`busyWaitMs`). */ function askAgainWhenTold(error: unknown, query: AnyQuery): void { - const wait = askAgainAfterMs(error); + const wait = tooManyRequests(error) + ? refusedTooMany(query, error).waitMs + : askAgainAfterMs(error); if (wait === undefined || askingAgain.has(query)) return; askingAgain.add(query); setTimeout( @@ -253,6 +377,10 @@ export const queryClient = new OpenBotQueryClient({ askAgainWhenTold(error, query); askWhetherStillMemberWhenRefused(error, query.queryKey); }, + // Answered: a later 429 starts a new run of refusals, waited from its own Retry-After. + onSuccess: (_data, query) => { + refusedAsTooMany.delete(query); + }, }), mutationCache: new MutationCache({ onError: (error) => { diff --git a/app/tests/learning-review.test.tsx b/app/tests/learning-review.test.tsx index 9a48d49681..a4a35b4481 100644 --- a/app/tests/learning-review.test.tsx +++ b/app/tests/learning-review.test.tsx @@ -745,7 +745,8 @@ test("a busy backend keeps the last review on screen and says the backend is bus const view = draw(); await view.findByText("Latest run finished."); busy = true; - await queryClient + // Not awaited: refused 429, the read is asked again quietly until it is answered (query-client.ts). + void queryClient .refetchQueries({ queryKey: ["learning", "review"] }) .catch(() => {}); expect( diff --git a/app/tests/organization-unavailable-chat.test.tsx b/app/tests/organization-unavailable-chat.test.tsx index 93218b92b5..3b62847f6b 100644 --- a/app/tests/organization-unavailable-chat.test.tsx +++ b/app/tests/organization-unavailable-chat.test.tsx @@ -14,6 +14,7 @@ import { style, UNAVAILABLE, } from "./organization-notices-browser"; +import { still } from "./page-still"; import { test } from "./renderer-crash"; /** @@ -48,16 +49,28 @@ afterAll(async () => { const BACKEND_UNREACHABLE = "OpenBot couldn't reach its backend, so your message wasn't sent. Try again, or quit and reopen OpenBot."; const CHOICES_FAILED = "Couldn't load the choices. Try again in a moment."; +/** The server's sentence for a person over its limit (429). */ +const TOO_MANY = "Too many call attempts. Try again in a moment."; /** A problem in OpenBot's own shape (RFC 9457), as the server answers a hold or a fault. */ function problem(status: number, detail: string, code: string) { return { type: `https://open.bot/errors/${code.toLowerCase().replaceAll("_", "-")}`, - title: status === 503 ? "Service unavailable." : "Unexpected server error.", + title: + status === 503 + ? "Service unavailable." + : status === 429 + ? "Too many requests." + : "Unexpected server error.", status, detail, code, - category: status === 503 ? "unavailable" : "internal", + category: + status === 503 + ? "unavailable" + : status === 429 + ? "rate_limit" + : "internal", retryable: true, requestId: "req_test", traceId: "trace_test", @@ -85,6 +98,8 @@ const BOT = { class ChatServer extends FakeServer { /** How a run is refused while Northwind is reachable: a server fault, said in red. */ runFails = false; + /** Or refused because the person asked too much of OpenBot at once (429), said calmly. */ + runTooMany = false; /** How the audit log's filter choices are answered while Northwind is reachable. */ choicesFail = false; @@ -155,6 +170,14 @@ class ChatServer extends FakeServer { contentType: "application/problem+json", headers: { "Retry-After": String(this.retryAfterSeconds) }, }; + // Over the server's limit for this person: 429 with its sentence and Retry-After. + if (this.runTooMany) + return { + status: 429, + json: problem(429, TOO_MANY, "RATE_LIMITED"), + contentType: "application/problem+json", + headers: { "Retry-After": "2" }, + }; if (this.runFails) return { status: 500, @@ -515,6 +538,88 @@ describe.skipIf(!asked)( }, }); }, 120_000); + + /* + * Over the server's limit, a run is refused 429 with a sentence and Retry-After. The runtime's + * client threw it as `REST run request failed: `, which read as a rule refusing the + * person: said in red under the message, for good. + */ + for (const engine of engines) + test(`a run refused for too many requests says the server's sentence calmly, in ${engine}`, async () => { + const look = LOOKS[0]; + const seen: Record = {}; + + { + const server = new ChatServer(); + server.runTooMany = true; + const page = await open(engine, look, server, "/conversation"); + try { + await page.getByText("1223").waitFor({ timeout: 15_000 }); + await send(page, "conversation", "What is 110 plus 707?"); + const stopped = page.getByTestId("transcript-stopped"); + await stopped.waitFor({ timeout: 15_000 }); + await still(page); + await shoot( + page, + "organization-unavailable-chat", + "conversation-too-many", + engine, + look, + ); + seen.conversation = { + says: (await stopped.innerText()).trim(), + drawn: await drawn(page, TOO_MANY), + backendUnreachable: await page + .getByText(/couldn't reach its backend/) + .count(), + }; + } finally { + await page.close(); + } + } + + { + const server = new ChatServer(); + server.runTooMany = true; + const page = await open( + engine, + look, + server, + "/bot?agent=general-assistant", + ); + try { + await page + .getByRole("heading", { name: "General Assistant" }) + .waitFor({ timeout: 15_000 }); + await still(page); + await send(page, "bot", "What is 110 plus 707?"); + const band = page.getByTestId("bot-chat-stopped"); + await band.waitFor({ timeout: 15_000 }); + await still(page); + await shoot( + page, + "organization-unavailable-chat", + "bot-page-too-many", + engine, + look, + ); + seen.botPage = { + says: (await band.innerText()).trim(), + drawn: await drawn(page, TOO_MANY), + backendUnreachable: await page + .getByText(/couldn't reach its backend/) + .count(), + }; + } finally { + await page.close(); + } + } + + expect(seen).toEqual({ + conversation: { says: TOO_MANY, drawn: CALM, backendUnreachable: 0 }, + botPage: { says: TOO_MANY, drawn: CALM, backendUnreachable: 0 }, + }); + }, 120_000); }, ); diff --git a/app/tests/too-many-requests-rules.test.ts b/app/tests/too-many-requests-rules.test.ts new file mode 100644 index 0000000000..18ed3e89f5 --- /dev/null +++ b/app/tests/too-many-requests-rules.test.ts @@ -0,0 +1,71 @@ +import { expect, test } from "bun:test"; +import { ClientError } from "@/lib/client"; +import { + failedRunReason, + laterRunFailure, + refusedForPerson, + stoppedReason, +} from "@/lib/copilot/stopped-turn"; +import { BUSY, isHeld, unavailableSaid } from "@/lib/load-failure"; +import { busyWaitMs } from "@/query-client"; + +/** + * The rules a 429 (too many requests from this person for now) is told and waited by, against what + * the server and the runtime's clients really send. + */ + +const SAID = "Too many call attempts. Try again in a moment."; +/** The server's 429, in problem details, as the API answers it. */ +const PROBLEM = `{"type":"https://open.bot/errors/rate-limited","title":"Too many requests.","status":429,"detail":"${SAID}","code":"RATE_LIMITED","category":"rate_limit","retryable":true,"requestId":"req_1","traceId":"t1"}`; + +test("a 429 is said calmly in the server's words, or OpenBot's when it sent none", () => { + expect( + unavailableSaid( + new ClientError(SAID, 429, "RATE_LIMITED", { detail: SAID }, 2_000), + ), + ).toBe(SAID); + // A proxy's 429, with no sentence of its own. + expect(unavailableSaid(new ClientError("That request failed.", 429))).toBe( + BUSY, + ); +}); + +test("a 429's wait is never sooner than Retry-After, doubles for each refusal in a row, and is a minute at most", () => { + expect(busyWaitMs(2_000, 1, 0)).toBe(2_000); + expect(busyWaitMs(2_000, 2, 0)).toBe(4_000); + expect(busyWaitMs(2_000, 3, 0.99)).toBeGreaterThanOrEqual(8_000); + expect(busyWaitMs(2_000, 3, 0.99)).toBeLessThanOrEqual(8_800); + expect(busyWaitMs(10_000, 9, 0.99)).toBe(60_000); + // A Retry-After of 0, or none, is a second. + expect(busyWaitMs(0, 1, 0)).toBe(1_000); + expect(busyWaitMs(undefined, 1, 0)).toBe(1_000); +}); + +test("a run the runtime refused 429 says the server's sentence calmly, not that the backend is unreachable or a rule refused it", async () => { + // Through Intelligence: the client's own prefix and the body as it came, the status gone. + const rest = new Error(`REST run request failed: ${PROBLEM}`); + // Over the plain event stream: AG-UI's HTTP agent keeps the status beside its own words. + const http = Object.assign(new Error(`HTTP 429: ${PROBLEM}`), { + status: 429, + }); + let askedAboutBot = false; + const noLongerUsable = async () => { + askedAboutBot = true; + return false; + }; + for (const refused of [rest, http]) { + expect(stoppedReason(refused)).toBe(SAID); + expect(laterRunFailure(refused)).toBe(SAID); + // Not a rule the person can't change: sent again later, it goes. + expect(refusedForPerson(refused)).toBe(false); + const reason = await failedRunReason( + refused, + "general-assistant", + noLongerUsable, + ); + expect(reason.message).toBe(SAID); + expect(isHeld(reason)).toBe(true); + } + // The server already said why: it isn't asked about the Bot, one more request while over its limit. + expect(askedAboutBot).toBe(false); +}); diff --git a/app/tests/too-many-requests.test.tsx b/app/tests/too-many-requests.test.tsx new file mode 100644 index 0000000000..213ad23a3b --- /dev/null +++ b/app/tests/too-many-requests.test.tsx @@ -0,0 +1,247 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + environmentManager, + focusManager, + QueryClientProvider, + useQuery, +} from "@tanstack/react-query"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import type { ReactNode } from "react"; +import { MemoryList, RememberFact } from "@/components/memory/memories"; +import { client } from "@/lib/client"; +import { failureSaid } from "@/lib/load-failure"; +import { queryClient } from "@/query-client"; +import { + MEMORY, + memoryBody, + memoryContract, + page, + problem, + requestOf, +} from "./learning-api"; +import { settleReactWork } from "./settle-react-work"; + +/** + * The server limits how much one person asks of it at once, and over the limit answers 429 in + * problem details with a sentence and Retry-After. Found on OpenBot Cloud: one person's home page + * polled hundreds of times a minute, every read refused 429 still drew "Couldn't load" in red, and + * each poll went out again on its own interval however often it was refused. + * + * Through the app's own query client and client, against answers shaped exactly as the server sends + * them (status, content type, Retry-After, the problem's members): + * + * - a polling read refused 429 keeps what it showed, says nothing, and is asked again after the + * Retry-After, never before; + * - refused again and again, each wait is longer, and once answered it polls as before; + * - a first load refused 429 keeps loading, then fills in with no failure drawn (Memory); + * - a press refused 429 says the server's own sentence, calmly (Memory's Remember a fact). + */ + +const NativeResponse = globalThis.Response; +const SAID = "Too many call attempts. Try again in a moment."; + +/** A refusal as the server answers one over its limit: 429, problem details, Retry-After in seconds. */ +function tooMany(retryAfterSeconds: number): Response { + const refused = problem(429, SAID, "RATE_LIMITED"); + return new NativeResponse(refused.body, { + status: 429, + headers: { + "content-type": "application/problem+json", + "retry-after": String(retryAfterSeconds), + }, + }); +} + +/** When each request reached the server, by path, in milliseconds since the epoch. */ +let asked: Record; +/** What each path answers next, in order; the last one stays. */ +let answers: Record Response)[]>; + +function serve(path: string, ...next: (() => Response)[]) { + answers[path] = next; +} + +const originalFetch = globalThis.fetch; +let wasServer = false; +beforeAll(() => GlobalRegistrator.register()); +beforeEach(() => { + asked = {}; + answers = {}; + queryClient.clear(); + // A page in a browser, in front of the person: Query polls, and retries, only then. + wasServer = environmentManager.isServer(); + environmentManager.setIsServer(() => false); + focusManager.setFocused(true); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = requestOf(input, init); + const key = `${request.method} ${request.path}`; + asked[key] = [...(asked[key] ?? []), Date.now()]; + const queue = answers[key]; + if (!queue || queue.length === 0) + return problem(404, "Not found.", "NOT_FOUND"); + const answer = queue.length > 1 ? queue.shift() : queue[0]; + return answer!(); + }) as typeof fetch; +}); +afterEach(async () => { + cleanup(); + await settleReactWork(); + queryClient.clear(); + focusManager.setFocused(undefined); + environmentManager.setIsServer(() => wasServer); + globalThis.fetch = originalFetch; +}); +afterAll(async () => { + await settleReactWork(); + await GlobalRegistrator.unregister(); +}); + +function draw(node: ReactNode) { + return render( + {node}, + ); +} + +const POLLED = "/api/v2/organizations/default/polled"; +const POLL_MS = 300; + +/** A screen's polling read, drawn as screens draw one: its answer, or its failure in a line of its own. */ +function Polled() { + const read = useQuery({ + queryKey: ["polled"], + queryFn: (): Promise => + client(POLLED, "value", { fallback: "Couldn't load it." }), + refetchInterval: POLL_MS, + }); + return ( +
    + {read.data === undefined ? null :

    {read.data}

    } + {read.error ?

    {failureSaid(read.error)}

    : null} +
    + ); +} + +const value = (said: string) => () => NativeResponse.json({ value: said }); + +/** Whatever the page shows as failed, at any moment of `ms` from now. */ +async function alertsOver(ms: number): Promise { + const seen = new Set(); + const until = Date.now() + ms; + while (Date.now() < until) { + for (const alert of document.querySelectorAll('[role="alert"]')) + seen.add(alert.textContent ?? ""); + await new Promise((resolve) => setTimeout(resolve, 25)); + } + return [...seen]; +} + +test("a polling read refused 429 keeps what it showed, says nothing, and asks again after Retry-After, not before", async () => { + serve(`GET ${POLLED}`, value("first"), () => tooMany(2), value("second")); + const view = draw(); + expect((await view.findByTestId("value")).textContent).toBe("first"); + + await waitFor(() => expect(asked[`GET ${POLLED}`]?.length).toBe(2), { + timeout: 2_000, + }); + // While it waits out the Retry-After: the answer it had, and nothing said about the refusal. + expect(await alertsOver(1_500)).toEqual([]); + expect(view.getByTestId("value").textContent).toBe("first"); + expect(asked[`GET ${POLLED}`]?.length).toBe(2); + + await waitFor( + () => expect(view.getByTestId("value").textContent).toBe("second"), + { timeout: 3_000 }, + ); + const [, refused = 0, again = 0] = asked[`GET ${POLLED}`] ?? []; + expect(again - refused).toBeGreaterThanOrEqual(2_000); + expect(view.queryByRole("alert")).toBeNull(); +}, 10_000); + +test("refused 429 again and again, a polling read waits longer each time, then polls as before once answered", async () => { + serve( + `GET ${POLLED}`, + value("first"), + () => tooMany(1), + () => tooMany(1), + () => tooMany(1), + value("second"), + ); + const view = draw(); + expect((await view.findByTestId("value")).textContent).toBe("first"); + await waitFor( + () => expect(view.getByTestId("value").textContent).toBe("second"), + { timeout: 12_000 }, + ); + expect(view.queryByRole("alert")).toBeNull(); + // Answered: back to its own interval. + await waitFor(() => expect(asked[`GET ${POLLED}`]?.length).toBe(7), { + timeout: 2_000, + }); + + const times = asked[`GET ${POLLED}`] ?? []; + const gaps = times.slice(1).map((at, i) => at - (times[i] ?? at)); + // The poll that was refused, then three waits after it: one Retry-After, doubled, doubled again. + expect(gaps[1]).toBeGreaterThanOrEqual(1_000); + expect(gaps[2]).toBeGreaterThanOrEqual(2_000); + expect(gaps[3]).toBeGreaterThanOrEqual(4_000); + // Then the read's own interval, not the last wait. + expect(gaps[5]).toBeLessThan(1_000); +}, 20_000); + +test("Memory's first load refused 429 keeps loading, then fills in with nothing said about it", async () => { + serve( + `GET ${MEMORY.memories}`, + () => tooMany(1), + () => tooMany(1), + () => + page(memoryContract.ListMemoriesResponse, "memories", [ + memoryBody({ + id: "m1", + content: "I prefer mornings.", + provenance: "You told a Bot", + updatedAt: "2026-10-09T10:00:00Z", + }), + ]), + ); + const seen = alertsOver(4_000); + const view = draw(); + expect( + await view.findByText("I prefer mornings.", {}, { timeout: 5_000 }), + ).toBeTruthy(); + expect(await seen).toEqual([]); + expect(view.queryByRole("alert")).toBeNull(); + expect(asked[`GET ${MEMORY.memories}`]?.length).toBe(3); +}, 10_000); + +test("Remember a fact refused 429 says the server's sentence, calmly, and isn't sent again by itself", async () => { + serve(`GET ${MEMORY.memories}`, () => + page(memoryContract.ListMemoriesResponse, "memories", []), + ); + serve(`POST ${MEMORY.memories}`, () => tooMany(3)); + const view = draw(); + const person = userEvent.setup({ document }); + await person.click(view.getByRole("button", { name: "Remember a fact" })); + await person.type( + await view.findByRole("textbox", { + name: "Something you want your Bots to know", + }), + "I work from Lisbon.", + ); + await person.click(view.getByRole("button", { name: "Remember" })); + + const alert = await view.findByRole("alert"); + expect(alert.textContent).toBe(SAID); + // Drawn as OpenBot asking to wait, not in the red kept for what failed. + expect(alert.querySelector("[data-held]")?.textContent).toBe(SAID); + await new Promise((resolve) => setTimeout(resolve, 1_000)); + expect(asked[`POST ${MEMORY.memories}`]?.length).toBe(1); +}, 10_000); diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs index 35085560d8..07fd78f97a 100644 --- a/desktop/src-tauri/src/connected/address.rs +++ b/desktop/src-tauri/src/connected/address.rs @@ -83,12 +83,24 @@ pub fn check(typed: &str) -> Result<(String, Metadata), Problem> { pub fn probe(address: &str) -> Result { let host = host_of(address); let client = http().map_err(|error| Kind::Unreachable.problem(&host, error))?; + // A 429 is that OpenBot answering, over its limit for now: never "there's no OpenBot", "too + // old" or "can't reach" (`rate_limited`). Asked again when the person tries again. let get = |path: &str| { - client + let answered = client .get(format!("{address}{path}")) .header(reqwest::header::ACCEPT, "application/json") .send() - .map_err(|error| Kind::Unreachable.problem(&host, transport(error))) + .map_err(|error| Kind::Unreachable.problem(&host, transport(error)))?; + if crate::rate_limited::is(answered.status().as_u16()) { + return Err(Kind::Busy.problem( + &host, + format!( + "GET {path} answered 429; retry after {}s", + crate::rate_limited::wait(answered.headers()).as_secs() + ), + )); + } + Ok(answered) }; let answered = get(DEPLOYMENT)?; @@ -349,6 +361,36 @@ mod tests { ); } + /// An OpenBot over its limit answers 429 to either question. It is there: never "there's no + /// OpenBot" or "too old", and never "couldn't reach". The person is told it is busy and tries + /// again, and it connects once the limit is lifted. + #[test] + fn an_openbot_over_its_limit_is_busy_not_missing() { + for path in [DEPLOYMENT, METADATA] { + let server = FakeOpenBot::start(Shape::Current); + server.rate_limit(path, 4); + let problem = check(&server.address()).expect_err("over its limit"); + assert_eq!(kind_of(&problem), Some(Kind::Busy), "{path}"); + assert_eq!( + problem.said, + format!( + "The OpenBot at {} is getting a lot of requests right now. Try again in a moment.", + host_of(&server.address()) + ) + ); + assert!( + problem + .detail + .as_deref() + .is_some_and(|detail| detail.contains("429") && detail.contains("4s")), + "{:?}", + problem.detail + ); + server.lift_rate_limit(path); + assert!(check(&server.address()).is_ok(), "{path}"); + } + } + #[test] fn a_web_page_and_json_that_is_not_openbots_are_not_an_openbot() { for shape in [Shape::WebPage, Shape::OtherJson] { diff --git a/desktop/src-tauri/src/connected/fake_openbot_tests.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs index 5d056ee9dd..7d87ea5237 100644 --- a/desktop/src-tauri/src/connected/fake_openbot_tests.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -133,6 +133,8 @@ struct State { /// The status of every gateway page it answered (`sign_in_ids::taken_then`), in order, as /// put on the response. gateway_answered: Vec, + /// Paths answered 429 for now, with the `Retry-After` each says: see `rate_limit`. + rate_limited: HashMap, } pub struct FakeOpenBot { @@ -364,6 +366,21 @@ impl FakeOpenBot { self.state.lock().unwrap().submitted.clone() } + /// From now on `path` is answered as the real OpenBot answers a person, an API key or an + /// organization over its limit: 429, `application/problem+json` with `code: RATE_LIMITED`, and + /// `Retry-After: `. Until `lift_rate_limit`. + pub fn rate_limit(&self, path: &str, seconds: u64) { + self.state + .lock() + .unwrap() + .rate_limited + .insert(path.to_owned(), seconds); + } + + pub fn lift_rate_limit(&self, path: &str) { + self.state.lock().unwrap().rate_limited.remove(path); + } + /// From now on the token endpoint answers only `delay` after a request arrives. The grant is /// decided, and a refresh token rotated, on arrival: a client that stops waiting has still /// used its refresh token up. @@ -440,11 +457,32 @@ async fn answer( ) }) .collect(); - state.lock().unwrap().seen.push(Seen { - method: method.clone(), - path: path.clone(), - headers: headers.clone(), - }); + let limited = { + let mut state = state.lock().unwrap(); + state.seen.push(Seen { + method: method.clone(), + path: path.clone(), + headers: headers.clone(), + }); + state.rate_limited.get(&path).copied() + }; + if let Some(seconds) = limited { + return Ok(Response::builder() + .status(StatusCode::TOO_MANY_REQUESTS) + .header("content-type", "application/problem+json") + .header("retry-after", seconds.to_string()) + .body(full( + serde_json::json!({ + "type": "https://open.bot/errors/rate-limited", + "title": "Too Many Requests", + "status": 429, + "code": "RATE_LIMITED", + "detail": "Too many call attempts. Try again in a moment.", + }) + .to_string(), + )) + .unwrap()); + } match &shape { Shape::WebPage => { diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index b16dface7b..bfa998eb83 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -39,6 +39,9 @@ pub const CLIENT_ID: &str = "openbot-desktop-oauth"; pub enum Kind { AddressInvalid, Unreachable, + /// That OpenBot answered, and is over its limit for now (429, `rate_limited`). Not + /// `Unreachable`, and never a sign-in that ended: the window offers Try again. + Busy, NotOpenBot, SinglePerson, TooOld, @@ -59,6 +62,7 @@ impl Kind { match self { Kind::AddressInvalid => "address-invalid", Kind::Unreachable => "unreachable", + Kind::Busy => "busy", Kind::NotOpenBot => "not-openbot", Kind::SinglePerson => "single-person", Kind::TooOld => "too-old", @@ -81,6 +85,10 @@ impl Kind { Kind::Unreachable => format!( "OpenBot couldn't reach {host}. Check the address and your network, then try again." ), + Kind::Busy => format!( + "The OpenBot at {host} is getting a lot of requests right now. Try again in a \ + moment." + ), Kind::NotOpenBot => format!( "There's no OpenBot at {host}. Check the address with whoever runs your OpenBot." ), @@ -133,6 +141,7 @@ pub fn kind_of(problem: &Problem) -> Option { [ Kind::AddressInvalid, Kind::Unreachable, + Kind::Busy, Kind::NotOpenBot, Kind::SinglePerson, Kind::TooOld, diff --git a/desktop/src-tauri/src/connected/relay.rs b/desktop/src-tauri/src/connected/relay.rs index c28f88d070..5ff5a23080 100644 --- a/desktop/src-tauri/src/connected/relay.rs +++ b/desktop/src-tauri/src/connected/relay.rs @@ -46,6 +46,11 @@ the page sees only the answer (`Forward::send`). The access token is replaced shortly before it ends, and when that OpenBot answers 401 to a request with no body the request is sent once more with a new one. When the refresh itself is refused the sign-in is over: the relay says so once (`Ended::SessionEnded`) and stops answering. + +A 429 from OpenBot (over its limit for a person, an API key or an organization) is an answer like +any other: passed to the page as it came, status, `Retry-After` and body, and never said to the +shell as `Ended::Unreachable`. A refresh answered 429 keeps the sign-in, and the page is answered a +429 of the same shape (`over_the_limit`) until the wait OpenBot gave is over (`rate_limited`). */ use super::sign_in::Session; @@ -532,7 +537,7 @@ async fn answer(mut request: Request, shared: Arc) -> Response let access = if signed_in { match token(&shared, None).await { Ok(access) => Some(access), - Err((status, said)) => return plain(status, said), + Err(answer) => return *answer, } } else { None @@ -586,7 +591,7 @@ async fn answer(mut request: Request, shared: Arc) -> Response }; } Ok(_) => {} - Err((status, said)) => return plain(status, said), + Err(answer) => return *answer, } } @@ -749,28 +754,65 @@ fn closed_unanswered(error: &reqwest::Error) -> bool { } /// An access token, off the async threads: a refresh is a blocking request. On a sign-in that has -/// ended, the relay says so and stops; the page is answered 401. +/// ended, the relay says so and stops; the page is answered 401. Over its limit, the OpenBot +/// answered the refresh 429: the page is answered 429 as the OpenBot answers one (`over_the_limit`), +/// and nothing is said to the shell, because the connection is fine. async fn token( shared: &Arc, refused: Option, -) -> Result { +) -> Result>> { let session = shared.session.clone(); let got = tokio::task::spawn_blocking(move || match refused { Some(used) => session.after_refused(&used), None => session.access(), }) .await; - match got { - Ok(Ok(access)) => Ok(access), + let answer = match got { + Ok(Ok(access)) => return Ok(access), Ok(Err(problem)) if kind_of(&problem) == Some(Kind::SessionEnded) => { end_session(shared); - Err((StatusCode::UNAUTHORIZED, "The sign-in has ended.")) + plain(StatusCode::UNAUTHORIZED, "The sign-in has ended.") + } + Ok(Err(problem)) if kind_of(&problem) == Some(Kind::Busy) => { + over_the_limit(shared.session.busy_for()) } Ok(Err(_)) | Err(_) => { say_unreachable(shared); - Err((StatusCode::BAD_GATEWAY, "OpenBot could not be reached.")) + plain(StatusCode::BAD_GATEWAY, "OpenBot could not be reached.") } - } + }; + Err(Box::new(answer)) +} + +/// The page's answer when the OpenBot is over its limit for the refresh its request needed: a 429 +/// shaped as the OpenBot's own (`application/problem+json`, `code: RATE_LIMITED`, `Retry-After` in +/// whole seconds), so the page waits and asks again exactly as it does for one the OpenBot sent. +fn over_the_limit(left: Option) -> Response { + let seconds = left + .map_or(crate::rate_limited::UNSAID, |left| { + // Whole seconds, rounded up: never sooner than the OpenBot said. + Duration::from_secs(left.as_secs() + u64::from(left.subsec_nanos() > 0)) + }) + .clamp(crate::rate_limited::AT_LEAST, crate::rate_limited::AT_MOST) + .as_secs(); + let problem = serde_json::json!({ + "type": "https://open.bot/errors/rate-limited", + "title": "Too Many Requests", + "status": 429, + "code": "RATE_LIMITED", + "detail": "OpenBot is getting a lot of requests right now. Try again in a moment.", + }); + Response::builder() + .status(StatusCode::TOO_MANY_REQUESTS) + .header(header::CONTENT_TYPE, "application/problem+json") + .header(header::CACHE_CONTROL, "no-store") + .header(header::RETRY_AFTER, seconds.to_string()) + .body( + Full::new(Bytes::from(problem.to_string())) + .map_err(|never| match never {}) + .boxed(), + ) + .expect("a 429 response") } fn end_session(shared: &Arc) { @@ -1392,6 +1434,105 @@ mod tests { ); } + /// OpenBot over its limit answers 429. That is an answer: the page gets it as it came (status, + /// `Retry-After`, the problem), the shell is not told the connection was lost, and the sign-in + /// is untouched. + #[test] + fn a_429_from_openbot_reaches_the_page_as_it_came_and_is_not_a_lost_connection() { + let rig = rig(); + let window = rig.window(); + rig.openbot.rate_limit(ECHO, 7); + + let answered = window.get(ECHO).send().unwrap(); + assert_eq!(answered.status(), 429); + assert_eq!(answered.headers()["retry-after"], "7"); + assert_eq!( + answered.headers()["content-type"], + "application/problem+json" + ); + let problem: serde_json::Value = answered.json().unwrap(); + assert_eq!(problem["code"], "RATE_LIMITED"); + assert_eq!( + problem["detail"], + "Too many call attempts. Try again in a moment." + ); + + std::thread::sleep(Duration::from_millis(300)); + assert!(rig.ended.lock().unwrap().is_empty()); + assert!(rig.store.get(&rig.openbot.address()).unwrap().is_some()); + rig.openbot.lift_rate_limit(ECHO); + window.echo(window.get(ECHO)); + } + + /* + * A refresh answered 429 ended the sign-in: anything but a 5xx from the token endpoint read as + * "signed out elsewhere", so the saved sign-in was forgotten and the person had to sign in + * again because OpenBot was busy for a few seconds. It is now kept, the page is answered 429 + * as OpenBot answers one, and the refresh is not asked again before the wait OpenBot gave. + */ + #[test] + fn a_refresh_over_the_limit_keeps_the_sign_in_and_the_page_waits_as_openbot_said() { + const TOKEN: &str = "/api/auth/oauth2/token"; + let rig = rig(); + let window = rig.window(); + let refreshes = || { + rig.openbot + .token_requests() + .iter() + .filter(|request| request["grant_type"] == "refresh_token") + .count() + }; + // The sign-in's own code exchange went there before. + let asked = || rig.openbot.seen_at(TOKEN).len() - 1; + rig.openbot.expire_access_tokens(); + rig.openbot.rate_limit(TOKEN, 2); + + let answered = window.get(ECHO).send().unwrap(); + assert_eq!(answered.status(), 429); + let wait: u64 = answered.headers()["retry-after"] + .to_str() + .unwrap() + .parse() + .unwrap(); + assert!((1..=2).contains(&wait), "{wait}"); + assert_eq!( + answered.headers()["content-type"], + "application/problem+json" + ); + let problem: serde_json::Value = answered.json().unwrap(); + assert_eq!(problem["code"], "RATE_LIMITED"); + assert_eq!(problem["status"], 429); + assert_eq!(asked(), 1); + + // Asked again at once: answered the same, and the refresh is not asked for again. + let again = window.get(ECHO).send().unwrap(); + assert_eq!(again.status(), 429); + assert_eq!(asked(), 1); + + std::thread::sleep(Duration::from_millis(300)); + assert!( + rig.ended.lock().unwrap().is_empty(), + "the shell was told {:?}", + rig.ended.lock().unwrap() + ); + assert!( + rig.store.get(&rig.openbot.address()).unwrap().is_some(), + "the saved sign-in was forgotten" + ); + + // Once the wait is over, the refresh goes through and the page's request with it. + rig.openbot.lift_rate_limit(TOKEN); + let deadline = Instant::now() + Duration::from_secs(10); + while rig.session.busy_for().is_some() { + assert!(Instant::now() < deadline, "the wait never ended"); + std::thread::sleep(Duration::from_millis(50)); + } + window.echo(window.get(ECHO)); + assert_eq!(asked(), 2); + assert_eq!(refreshes(), 1, "the refresh OpenBot answered"); + assert!(rig.ended.lock().unwrap().is_empty()); + } + /// A page in the person's own browser, or another program on this computer, can send a /// request to `127.0.0.1:` with the right `Host`. It does not have the run's secret, /// so it is refused and OpenBot never hears of it. diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs index e306733c5c..fc45363108 100644 --- a/desktop/src-tauri/src/connected/sign_in.rs +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -169,6 +169,9 @@ struct Live { expires: Instant, /// When a refused access token last led to a refresh (`REFUSED_REFRESH_EVERY`). refreshed_after_refusal: Option, + /// Until when the OpenBot asked not to be asked for a refresh again (429 and its + /// `Retry-After`, `rate_limited`). Until then a refresh is not asked for: the answer is `busy`. + busy_until: Option, ended: bool, } @@ -192,6 +195,9 @@ enum Refused { Transport(String), /// The OpenBot answered no: its status and its OAuth error code. Answer { status: u16, error: String }, + /// The OpenBot answered 429: over its limit for now, and asked again after this long. It + /// said nothing about the grant, so the sign-in is as good as it was. + Busy(Duration), } impl Refused { @@ -199,6 +205,9 @@ impl Refused { match self { Refused::Transport(error) => format!("{what}: {error}"), Refused::Answer { status, error } => format!("{what} answered {status} {error}"), + Refused::Busy(wait) => { + format!("{what} answered 429; retry after {}s", wait.as_secs()) + } } } } @@ -293,6 +302,7 @@ fn finish( Refused::Transport(_) => { Kind::Unreachable.problem(&host, refused.detail("the token exchange")) } + Refused::Busy(_) => Kind::Busy.problem(&host, refused.detail("the token exchange")), Refused::Answer { .. } => failed(refused.detail("the token exchange")), })?; let Some(refresh) = granted.refresh else { @@ -310,6 +320,7 @@ fn finish( refresh, expires: Instant::now() + Duration::from_secs(granted.expires_in), refreshed_after_refusal: None, + busy_until: None, ended: false, }), refreshing: OneAtATime::default(), @@ -352,6 +363,7 @@ pub fn resume(address: &str, metadata: &Metadata, store: Store) -> Result Result { + // Not asked again before the OpenBot said to: every request the window makes would + // otherwise ask for a refresh while it is over its limit. + if let Some(wait) = self.busy_for() { + return Err(Kind::Busy.problem( + &self.host, + format!("the refresh is asked again in {}s", wait.as_secs().max(1)), + )); + } let old = self.live.lock().unwrap().refresh.clone(); let granted = token_request( &self.token_endpoint, @@ -502,6 +522,19 @@ impl Session { Err(Refused::Transport(error)) => { return Err(Kind::Unreachable.problem(&self.host, format!("the refresh: {error}"))) } + // Over its limit: it answered, and said nothing about the sign-in, which is kept. + // Asked again after the wait it gave, and said as busy, never as out of reach. + Err(Refused::Busy(wait)) => { + self.live.lock().unwrap().busy_until = Some(Instant::now() + wait); + log::info!( + "[connect] {} is over its limit; the refresh is asked again in {}s", + self.host, + wait.as_secs() + ); + return Err( + Kind::Busy.problem(&self.host, Refused::Busy(wait).detail("the refresh")) + ); + } // Only the OpenBot saying the grant itself is dead (RFC 6749 §5.2) ends the sign-in. Err(Refused::Answer { status, error }) if matches!(status, 400 | 401) @@ -519,7 +552,7 @@ impl Session { log::info!("[connect] the sign-in to {} has ended", self.host); return Err(self.ended(refused.detail("the refresh"))); } - // Rate limited, forbidden, a gateway, a redirect, an unreadable body: the OpenBot did + // Forbidden, a gateway, a redirect, an unreadable body: the OpenBot did // not say the sign-in is dead, so it is kept and the stored token is left as it is. Err(refused) => { log::warn!( @@ -544,12 +577,24 @@ impl Session { live.access = granted.access.clone(); live.refresh = refresh; live.expires = Instant::now() + Duration::from_secs(granted.expires_in); + live.busy_until = None; if after_refusal { live.refreshed_after_refusal = Some(Instant::now()); } Ok(granted.access) } + /// How much longer the OpenBot asked not to be asked for a refresh (`Kind::Busy`), when it + /// still is that long. + pub fn busy_for(&self) -> Option { + self.live + .lock() + .unwrap() + .busy_until + .map(|until| until.saturating_duration_since(Instant::now())) + .filter(|left| !left.is_zero()) + } + /// The access token in hand, when it can be used as it is. fn usable(&self, refused: Option<&str>) -> Result, Problem> { let live = self.live.lock().unwrap(); @@ -575,6 +620,7 @@ impl Session { - 401 or 403: the person signed in, and that OpenBot does not let this sign-in in on the app's screens (`access-refused`). Updating OpenBot is not the way on, so it is not `too-old`. - 404: its release does not serve that address (`too-old`). + - 429: it is over its limit for now (`busy`), and the person tries again. - Anything else that is not a success: `sign-in-failed`. */ fn serves_the_app(&self) -> Result<(), Problem> { @@ -596,6 +642,7 @@ impl Session { 200..=299 => Ok(()), 401 | 403 => Err(Kind::AccessRefused.problem(&self.host, said())), 404 => Err(Kind::TooOld.problem(&self.host, said())), + 429 => Err(Kind::Busy.problem(&self.host, said())), status => Err(Kind::SignInFailed.problem( &self.host, format!("GET /api/copilotkit/info answered {status}"), @@ -759,6 +806,9 @@ fn token_request(endpoint: &str, form: &[(&str, &str)]) -> Result Result { .map_err(|error| format!("Could not create connection status client: {error}")) } -pub fn poll(client: &Client, port: u16, token: &str) -> Result, String> { +/// Why a poll gave no status. +#[derive(Debug, PartialEq, Eq)] +pub enum PollFailure { + /// The server answered 429: over its limit, and to be asked again after this long + /// (`rate_limited`). It answered, so it is not a server that has gone quiet. + Busy(std::time::Duration), + /// No answer, or one that was not a status. + Failed(String), +} + +impl std::fmt::Display for PollFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Busy(wait) => write!( + f, + "Connection status request was over the server's limit; asked again in {}s.", + wait.as_secs() + ), + Self::Failed(said) => f.write_str(said), + } + } +} + +pub fn poll(client: &Client, port: u16, token: &str) -> Result, PollFailure> { + let failed = |said: String| PollFailure::Failed(said); let response = client .get(format!( "http://127.0.0.1:{port}/api/desktop/connection-failure" )) .header("x-openbot-desktop-host-token", token) .send() - .map_err(|error| format!("Connection status request failed: {error}"))?; + .map_err(|error| failed(format!("Connection status request failed: {error}")))?; // Older installed payloads have no status endpoint. This is a capability check, not auth. if response.status() == reqwest::StatusCode::NOT_FOUND { return Ok(None); } + if openbot_desktop_lib::rate_limited::is(response.status().as_u16()) { + return Err(PollFailure::Busy(openbot_desktop_lib::rate_limited::wait( + response.headers(), + ))); + } if !response.status().is_success() { - return Err(format!( + return Err(failed(format!( "Connection status request returned HTTP {}.", response.status() - )); + ))); } let failure = response .json::>() - .map_err(|_| "Connection status response was invalid.".to_string())?; + .map_err(|_| failed("Connection status response was invalid.".to_string()))?; match failure { None => Ok(None), Some(Failure { connection, code }) => match (connection.as_str(), code.as_str()) { @@ -47,7 +76,9 @@ pub fn poll(client: &Client, port: u16, token: &str) -> Result { Ok(Some(Connection::Intelligence)) } - _ => Err("Connection status response contained an unsupported failure.".into()), + _ => Err(failed( + "Connection status response contained an unsupported failure.".into(), + )), }, } } @@ -117,4 +148,31 @@ mod tests { assert_eq!(result.map_err(|_| ()), expected); } } + + /// A server over its limit answered: the watcher is told how long to wait, never that the + /// server stopped answering. + #[test] + fn a_429_says_how_long_to_wait_and_is_not_a_silent_server() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body = r#"{"type":"https://open.bot/errors/rate-limited","title":"Too Many Requests","status":429,"code":"RATE_LIMITED","detail":"Too many call attempts. Try again in a moment."}"#; + write!(stream, "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/problem+json\r\nRetry-After: 7\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); + }); + let result = poll(&client().unwrap(), port, "synthetic-run-token"); + server.join().unwrap(); + assert_eq!( + result, + Err(PollFailure::Busy(std::time::Duration::from_secs(7))) + ); + } } diff --git a/desktop/src-tauri/src/host_access.rs b/desktop/src-tauri/src/host_access.rs index a3a26bd532..cbec0a6088 100644 --- a/desktop/src-tauri/src/host_access.rs +++ b/desktop/src-tauri/src/host_access.rs @@ -622,16 +622,33 @@ enum ServerFailure { NoAnswer(String), /// It answered, and not as it should: another token, an older server, an unreadable body. Answered(String), + /// It answered 429: over its limit for now, and to be asked again after this long + /// (`rate_limited`). It is there and the token is good, so nothing here ends. + Busy(Duration), } impl std::fmt::Display for ServerFailure { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NoAnswer(said) | Self::Answered(said) => f.write_str(said), + Self::Busy(wait) => write!( + f, + "the server is over its limit; asked again in {}s", + wait.as_secs() + ), } } } +/// The server's answer read as a `ServerFailure` when it is not a success: `Busy` for a 429, else +/// `Answered` with `what` and the status. +fn answered_failure(response: &reqwest::blocking::Response, what: &str) -> ServerFailure { + if crate::rate_limited::is(response.status().as_u16()) { + return ServerFailure::Busy(crate::rate_limited::wait(response.headers())); + } + ServerFailure::Answered(format!("{what} failed with HTTP {}", response.status())) +} + /** Asks the server for the next operation, once a poll interval, until Stop. @@ -649,6 +666,9 @@ token, a server older than the route), and Stop and Quit, which stop this broker them. A restart the container engine makes alone is held the same way: nothing here can tell it from one the Status window asked for, and the host token, which survives both, is what proves the server that comes back is this computer's own. + +A 429 (the server over its limit, `rate_limited`) is the server answering. It ends nothing, not +the folders and not the work in flight, and the next ask waits for the `Retry-After` it gave. */ fn broker_loop(inner: Arc) { let client = match Client::builder() @@ -673,6 +693,12 @@ fn broker_loop(inner: Arc) { ); holding_since = None; } + // Back, and over its limit: it answered, so it is not away. The folders stay held + // and are offered again once the wait it gave is over. + Err(ServerFailure::Busy(wait)) => { + inner.rest(wait); + continue; + } Err(ServerFailure::NoAnswer(error)) => { if since.elapsed() >= inner.config.server_away_grace { log::warn!( @@ -703,6 +729,15 @@ fn broker_loop(inner: Arc) { match inner.next_operation(&client) { Ok(Some(operation)) => inner.spawn_operation(client.clone(), operation), Ok(None) => thread::sleep(inner.config.poll_interval), + // Over its limit: the grants and the work in flight are as good as they were. Asked + // again only after the wait it gave, never at the usual interval. + Err(ServerFailure::Busy(wait)) => { + log::info!( + "[host access] the server is over its limit; asking again in {} s", + wait.as_secs() + ); + inner.rest(wait); + } Err(ServerFailure::NoAnswer(error)) if inner.holds_live_grants() => { log::warn!( "[host access] the server is not answering; holding this computer's folders for up to {} s while it comes back: {error}", @@ -730,6 +765,20 @@ impl Inner { self.state.lock().expect("host state poisoned").stopped } + /// Waits `wait`, and at least a poll interval, before the next ask: a server over its limit + /// said how long (`ServerFailure::Busy`). In steps, so Stop ends the wait. + fn rest(&self, wait: Duration) { + let until = Instant::now() + wait.max(self.config.poll_interval); + let step = self.config.poll_interval.max(Duration::from_millis(10)); + while !self.is_stopped() { + let left = until.saturating_duration_since(Instant::now()); + if left.is_zero() { + return; + } + thread::sleep(left.min(step)); + } + } + fn revoke_all_and_stop(&self) -> HostAccessResult<()> { self.end_work(true) } @@ -798,10 +847,7 @@ impl Inner { ServerFailure::NoAnswer(format!("Could not hand the folders back: {error}")) })?; if !response.status().is_success() { - return Err(ServerFailure::Answered(format!( - "Handing the folders back failed with HTTP {}", - response.status() - ))); + return Err(answered_failure(&response, "Handing the folders back")); } let restored = response.json::().map_err(|error| { ServerFailure::Answered(format!( @@ -865,10 +911,7 @@ impl Inner { ServerFailure::NoAnswer(format!("Could not poll host operation: {error}")) })?; if !response.status().is_success() { - return Err(ServerFailure::Answered(format!( - "Host operation poll failed with HTTP {}", - response.status() - ))); + return Err(answered_failure(&response, "Host operation poll")); } let poll = response.json::().map_err(|error| { ServerFailure::Answered(format!( @@ -4013,6 +4056,9 @@ mod tests { assert!(inner.require_grant(&operation).is_err()); } + /// The body of the server's 429, as the real one sends it. + const OVER_THE_LIMIT: &str = r#"{"type":"https://open.bot/errors/rate-limited","title":"Too Many Requests","status":429,"code":"RATE_LIMITED","detail":"Too many call attempts. Try again in a moment."}"#; + /// A server the broker polls that can be taken down and brought back on the same address, as a /// restart does: while down it drops every connection unanswered. Records what it answered. struct RestartingServer { @@ -4020,6 +4066,8 @@ mod tests { up: Arc, /// What it answers a hand-back with. restore_status: Arc>, + /// While set, a poll is answered 429 with this `Retry-After`, as a server over its limit. + polls_limited: Arc>>, seen: Arc>>, dropped: Arc, done: Arc, @@ -4033,6 +4081,7 @@ mod tests { let base_url = format!("http://{}", listener.local_addr().unwrap()); let up = Arc::new(std::sync::atomic::AtomicBool::new(true)); let restore_status = Arc::new(Mutex::new(200_u16)); + let polls_limited = Arc::new(Mutex::new(None)); let seen = Arc::new(Mutex::new(Vec::new())); let dropped = Arc::new(AtomicUsize::new(0)); let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -4043,6 +4092,7 @@ mod tests { dropped.clone(), done.clone(), ); + let worker_limited = polls_limited.clone(); let thread = thread::spawn(move || loop { let mut stream = match listener.accept() { Ok((stream, _)) => stream, @@ -4096,27 +4146,46 @@ mod tests { continue; } let body = String::from_utf8(body).unwrap(); - let (status, answer) = if path.ends_with("/desktop/next") { - (200, r#"{"operations":[],"leaseMs":15000}"#.to_string()) - } else if path.ends_with("/desktop/restore") { - let status = *worker_status.lock().unwrap(); - let presented: serde_json::Value = serde_json::from_str(&body).unwrap(); - let restored = presented["grants"] - .as_array() - .unwrap() - .iter() - .map(|grant| grant["grantId"].clone()) - .collect::>(); + let limited = *worker_limited.lock().unwrap(); + let (status, answer) = + if let (true, Some(_)) = (path.ends_with("/desktop/next"), limited) { + (429, OVER_THE_LIMIT.to_string()) + } else if path.ends_with("/desktop/next") { + (200, r#"{"operations":[],"leaseMs":15000}"#.to_string()) + } else if path.ends_with("/desktop/restore") { + let status = *worker_status.lock().unwrap(); + let presented: serde_json::Value = serde_json::from_str(&body).unwrap(); + let restored = presented["grants"] + .as_array() + .unwrap() + .iter() + .map(|grant| grant["grantId"].clone()) + .collect::>(); + ( + status, + serde_json::json!({ "restored": restored }).to_string(), + ) + } else { + (404, "{}".to_string()) + }; + worker_seen.lock().unwrap().push((path, body)); + // A 429 is the real one's: a problem, and how long to wait (one second for a + // hand-back over the limit). + let (kind, wait) = if status == 429 { ( - status, - serde_json::json!({ "restored": restored }).to_string(), + "application/problem+json", + format!("Retry-After: {}\r\n", limited.unwrap_or(1)), ) } else { - (404, "{}".to_string()) + ("application/json", String::new()) + }; + let answer = if status == 429 { + OVER_THE_LIMIT.to_string() + } else { + answer }; - worker_seen.lock().unwrap().push((path, body)); let response = format!( - "HTTP/1.1 {status} Answer\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", + "HTTP/1.1 {status} Answer\r\nContent-Type: {kind}\r\n{wait}Content-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len() ); let _ = stream.write_all(response.as_bytes()); @@ -4125,6 +4194,7 @@ mod tests { base_url, up, restore_status, + polls_limited, seen, dropped, done, @@ -4302,6 +4372,72 @@ mod tests { let _ = fs::remove_dir_all(root); } + /* + * A server over its limit answers 429. The broker read that as a failed poll and ended every + * folder the person had approved, then asked again at its usual interval, which kept the server + * over its limit. A 429 is the server answering: the folders stay, and the next ask waits for + * the Retry-After it gave. The same for a hand-back after a restart. + */ + #[test] + fn a_server_over_its_limit_keeps_the_folders_and_is_asked_again_only_after_its_wait() { + let server = RestartingServer::start(); + let (host, root) = polling_broker(&server, Duration::from_secs(60)); + wait_until("the broker polled", || server.asked("/desktop/next") >= 2); + + *server.polls_limited.lock().unwrap() = Some(1); + let before = server.asked("/desktop/next"); + wait_until("a poll was answered 429", || { + server.asked("/desktop/next") > before + }); + let limited_at = Instant::now(); + let answered_429 = server.asked("/desktop/next"); + // The poll interval is 20 ms: at that pace this would be some thirty more polls. + thread::sleep(Duration::from_millis(600)); + assert!( + server.asked("/desktop/next") <= answered_429 + 1, + "asked {} more times within the second it said to wait", + server.asked("/desktop/next") - answered_429 + ); + assert!(grant_is_live(&host), "a 429 ended the folders"); + + *server.polls_limited.lock().unwrap() = None; + wait_until("the broker asked again", || { + server.asked("/desktop/next") > answered_429 + 1 + }); + assert!(limited_at.elapsed() >= Duration::from_millis(900)); + assert!(grant_is_live(&host)); + host.stop_with_machine_stopped(); + let _ = fs::remove_dir_all(root); + + // Back after a restart, and over its limit for the hand-back: still held, offered again + // after the wait, and taken. + let server = RestartingServer::start(); + *server.restore_status.lock().unwrap() = 429; + let (host, root) = polling_broker(&server, Duration::from_secs(60)); + wait_until("the broker polled", || server.asked("/desktop/next") >= 1); + restart(&server); + wait_until("the folders were offered back", || { + server.asked("/desktop/restore") >= 1 + }); + thread::sleep(Duration::from_millis(500)); + assert_eq!(server.asked("/desktop/restore"), 1, "asked again too soon"); + assert!( + grant_is_live(&host), + "a 429 to the hand-back ended the folders" + ); + *server.restore_status.lock().unwrap() = 200; + wait_until("the folders were offered back again", || { + server.asked("/desktop/restore") >= 2 + }); + let polls = server.asked("/desktop/next"); + wait_until("the broker polled after the hand-back", || { + server.asked("/desktop/next") > polls + }); + assert!(grant_is_live(&host)); + host.stop_with_machine_stopped(); + let _ = fs::remove_dir_all(root); + } + #[test] fn stop_waits_for_a_folder_hand_back_already_in_flight() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index ad777ee17c..2eb86ea904 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -49,6 +49,7 @@ pub mod provider; pub mod provider_oauth; pub mod pull_metrics; pub mod quiet; +pub mod rate_limited; pub mod recorder_external; pub mod recorder_host; pub mod recorder_install; diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index ff739f4695..4d0a0c3c26 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -12923,6 +12923,9 @@ fn publish_connection_failure( /// up. Longer than the server takes to come back after its restart policy restarts it. const SERVER_GONE_AFTER: std::time::Duration = std::time::Duration::from_secs(10); +/// How often the watcher asks a running OpenBot for a refused connection. +const WATCH_EVERY: std::time::Duration = std::time::Duration::from_secs(2); + /** Watch a running OpenBot for a connection it reports refused, and send the window back to setup to refresh it. @@ -12954,9 +12957,12 @@ fn watch_connections( let mut setup_shown = false; // Whether the log has said, for this silence, that the server is up and left to finish. let mut busy_said = false; + // How long until the next ask: two seconds, or the wait a server over its limit gave. + let mut next_ask_after = WATCH_EVERY; loop { - std::thread::sleep(std::time::Duration::from_secs(2)); + std::thread::sleep(next_ask_after); + next_ask_after = WATCH_EVERY; let shell = app.state::(); // Not this run's any more, or no run at all. if shell.generation.load(std::sync::atomic::Ordering::SeqCst) != generation @@ -12972,7 +12978,8 @@ fn watch_connections( continue; } let polled = desktop_connection::poll(&client, server_port, &token); - if polled.is_ok() { + // A 429 is the server answering, over its limit: not a silence. + if !matches!(polled, Err(desktop_connection::PollFailure::Failed(_))) { if busy_said { log::info!("[watch] OpenBot is answering again"); } @@ -12991,6 +12998,14 @@ fn watch_connections( } } Ok(None) => {} + // Asked again only after the wait it gave, never at the usual two seconds. + Err(desktop_connection::PollFailure::Busy(wait)) => { + log::info!( + "[watch] OpenBot is over its limit; asking again in {}s", + wait.as_secs() + ); + next_ask_after = wait.max(WATCH_EVERY); + } Err(error) => { if !poll_failed { log::warn!("[watch] {error}"); diff --git a/desktop/src-tauri/src/rate_limited.rs b/desktop/src-tauri/src/rate_limited.rs new file mode 100644 index 0000000000..3b09289f0e --- /dev/null +++ b/desktop/src-tauri/src/rate_limited.rs @@ -0,0 +1,71 @@ +/*! +An OpenBot over its limit for a person, an API key or an organization answers 429 (a +`application/problem+json` with `code: RATE_LIMITED`), and says in `Retry-After`, in whole seconds, +how long to wait before asking again. + +That is an answer. OpenBot is there and is asking to be asked again later, so nothing in this app +reads a 429 as OpenBot being unreachable, a lost connection or a sign-in that ended. A loop that +asks OpenBot again and again waits at least as long as it says before the next ask, whatever its +own interval is. A one-shot write is not sent again for it. +*/ + +use std::time::Duration; + +/// The shortest wait after a 429, whatever it said: a `Retry-After: 0` would otherwise ask again +/// at once, which is what the limit is there to stop. +pub const AT_LEAST: Duration = Duration::from_secs(1); +/// The longest: an OpenBot says 1 to 10 seconds, and a wait longer than a minute reads to a person +/// as the app having stopped. +pub const AT_MOST: Duration = Duration::from_secs(60); +/// When the answer names no wait this app can read (none, or an HTTP date): the move to OpenBot +/// Cloud's wait for the same case (`move_to_cloud`). +pub const UNSAID: Duration = Duration::from_secs(5); + +/// Whether `status` is OpenBot saying it is over its limit. +pub fn is(status: u16) -> bool { + status == 429 +} + +/// How long to wait before asking again, from the answer's headers. +pub fn wait(headers: &reqwest::header::HeaderMap) -> Duration { + seconds( + headers + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.trim().parse::().ok()), + ) +} + +/// How long to wait for a `Retry-After` of `said` seconds, or none. +pub fn seconds(said: Option) -> Duration { + said.map_or(UNSAID, Duration::from_secs) + .clamp(AT_LEAST, AT_MOST) +} + +#[cfg(test)] +mod tests { + use super::*; + use reqwest::header::{HeaderMap, HeaderValue, RETRY_AFTER}; + + fn said(value: &str) -> Duration { + let mut headers = HeaderMap::new(); + headers.insert(RETRY_AFTER, HeaderValue::from_str(value).unwrap()); + wait(&headers) + } + + /// What OpenBot sends (whole seconds, usually 1 to 10) is waited as said. Anything else is + /// kept between one second and a minute. + #[test] + fn the_wait_is_what_openbot_said_kept_between_a_second_and_a_minute() { + assert_eq!(said("1"), Duration::from_secs(1)); + assert_eq!(said("7"), Duration::from_secs(7)); + assert_eq!(said(" 10 "), Duration::from_secs(10)); + assert_eq!(said("0"), AT_LEAST); + assert_eq!(said("3600"), AT_MOST); + assert_eq!(said("Wed, 21 Oct 2026 07:28:00 GMT"), UNSAID); + assert_eq!(said("-3"), UNSAID); + assert_eq!(wait(&HeaderMap::new()), UNSAID); + assert!(is(429)); + assert!(!is(503)); + } +} From 6ee661ec012e45ec08064d56a614932daa1cd9a1 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 15:31:56 -0800 Subject: [PATCH 013/224] Colourful chart series in OpenBot's own hues (#2564) The five chart colours were grays of slate: the first was 1.5:1 on a light card and the last nearly black on a dark one, so every chart read as gray and some series could hardly be seen. They are now OpenBot's own hues, in an order that keeps neighbours apart: the brand blue, warning's amber, success's teal, destructive's rose and the sidebar's violet. Each is set separately for light and dark, at least 3:1 against the card in its mode, and the five stay apart for protan, deutan and tritan colour vision. A test holds all three, and fails on the old values. --- app/src/theme.css | 20 +++--- mobile/src/scheme.ts | 20 +++--- tokens/src/scheme.ts | 26 +++++--- tokens/tests/chart.test.ts | 121 +++++++++++++++++++++++++++++++++++++ tokens/tests/slate.test.ts | 2 +- 5 files changed, 158 insertions(+), 31 deletions(-) create mode 100644 tokens/tests/chart.test.ts diff --git a/app/src/theme.css b/app/src/theme.css index 7342894c1b..eac4bc61d1 100644 --- a/app/src/theme.css +++ b/app/src/theme.css @@ -27,11 +27,11 @@ --border: oklch(0.108 0.042 264.7 / 20%); --input: oklch(0.108 0.042 264.7 / 20%); --ring: oklch(0.644 0.167 276.1); - --chart-1: oklch(0.869 0.022 252.894); - --chart-2: oklch(0.554 0.046 257.417); - --chart-3: oklch(0.446 0.043 257.281); - --chart-4: oklch(0.372 0.044 257.287); - --chart-5: oklch(0.279 0.041 260.031); + --chart-1: oklch(0.46 0.2 264); + --chart-2: oklch(0.66 0.146 66); + --chart-3: oklch(0.62 0.122 170); + --chart-4: oklch(0.5 0.2 18); + --chart-5: oklch(0.6 0.2 286); --empty-pattern-color: oklch(0.746 0.117 279.9); --sidebar: oklch(0.948 0.01 251.8); --sidebar-foreground: oklch(0.108 0.042 264.7); @@ -77,11 +77,11 @@ --border: oklch(0.956 0.004 252 / 16%); --input: oklch(0.956 0.004 252 / 16%); --ring: oklch(0.713 0.151 277.7); - --chart-1: oklch(0.869 0.022 252.894); - --chart-2: oklch(0.554 0.046 257.417); - --chart-3: oklch(0.446 0.043 257.281); - --chart-4: oklch(0.372 0.044 257.287); - --chart-5: oklch(0.279 0.041 260.031); + --chart-1: oklch(0.58 0.2 264); + --chart-2: oklch(0.76 0.168 66); + --chart-3: oklch(0.86 0.17 170); + --chart-4: oklch(0.6 0.2 18); + --chart-5: oklch(0.76 0.128 286); --empty-pattern-color: oklch(0.832 0.085 281.4); --sidebar: oklch(0.156 0.017 252); --sidebar-foreground: oklch(0.956 0.004 252); diff --git a/mobile/src/scheme.ts b/mobile/src/scheme.ts index d8123ea2c7..17c62421af 100644 --- a/mobile/src/scheme.ts +++ b/mobile/src/scheme.ts @@ -23,11 +23,11 @@ export const scheme = { border: "#01031333", input: "#01031333", ring: "#7480f1", - "chart-1": "#cad5e2", - "chart-2": "#62748e", - "chart-3": "#45556c", - "chart-4": "#314158", - "chart-5": "#1d293d", + "chart-1": "#1949c5", + "chart-2": "#cd7d04", + "chart-3": "#049d7b", + "chart-4": "#ba0135", + "chart-5": "#7b65ef", "empty-pattern-color": "#9ea4f5", sidebar: "#e9eef4", "sidebar-foreground": "#010313", @@ -59,11 +59,11 @@ export const scheme = { border: "#eef1f329", input: "#eef1f329", ring: "#8d97ff", - "chart-1": "#cad5e2", - "chart-2": "#62748e", - "chart-3": "#45556c", - "chart-4": "#314158", - "chart-5": "#1d293d", + "chart-1": "#3a70ee", + "chart-2": "#f79807", + "chart-3": "#03f4c0", + "chart-4": "#de3951", + "chart-5": "#aaa4ff", "empty-pattern-color": "#bec2ff", sidebar: "#070d14", "sidebar-foreground": "#eef1f3", diff --git a/tokens/src/scheme.ts b/tokens/src/scheme.ts index 610c4e84b3..962135d5fb 100644 --- a/tokens/src/scheme.ts +++ b/tokens/src/scheme.ts @@ -84,11 +84,17 @@ const light: Palette = { border: "oklch(0.108 0.042 264.7 / 20%)", input: "oklch(0.108 0.042 264.7 / 20%)", ring: "oklch(0.644 0.167 276.1)", - "chart-1": "oklch(0.869 0.022 252.894)", - "chart-2": "oklch(0.554 0.046 257.417)", - "chart-3": "oklch(0.446 0.043 257.281)", - "chart-4": "oklch(0.372 0.044 257.287)", - "chart-5": "oklch(0.279 0.041 260.031)", + /* + * The chart series are OpenBot's own hues: the brand blue, warning's amber, success's teal, + * destructive's rose and the sidebar's violet. Each is clearly colourful and at least 3:1 against + * the card in its mode, and the order keeps neighbours apart for protan, deutan and tritan + * colour vision (tokens/tests/chart.test.ts holds both). + */ + "chart-1": "oklch(0.46 0.2 264)", + "chart-2": "oklch(0.66 0.146 66)", + "chart-3": "oklch(0.62 0.122 170)", + "chart-4": "oklch(0.5 0.2 18)", + "chart-5": "oklch(0.6 0.2 286)", "empty-pattern-color": "oklch(0.746 0.117 279.9)", sidebar: "oklch(0.948 0.01 251.8)", "sidebar-foreground": "oklch(0.108 0.042 264.7)", @@ -128,11 +134,11 @@ const dark: Palette = { border: "oklch(0.956 0.004 252 / 16%)", input: "oklch(0.956 0.004 252 / 16%)", ring: "oklch(0.713 0.151 277.7)", - "chart-1": "oklch(0.869 0.022 252.894)", - "chart-2": "oklch(0.554 0.046 257.417)", - "chart-3": "oklch(0.446 0.043 257.281)", - "chart-4": "oklch(0.372 0.044 257.287)", - "chart-5": "oklch(0.279 0.041 260.031)", + "chart-1": "oklch(0.58 0.2 264)", + "chart-2": "oklch(0.76 0.168 66)", + "chart-3": "oklch(0.86 0.17 170)", + "chart-4": "oklch(0.6 0.2 18)", + "chart-5": "oklch(0.76 0.128 286)", "empty-pattern-color": "oklch(0.832 0.085 281.4)", sidebar: "oklch(0.156 0.017 252)", "sidebar-foreground": "oklch(0.956 0.004 252)", diff --git a/tokens/tests/chart.test.ts b/tokens/tests/chart.test.ts new file mode 100644 index 0000000000..cd9e0c30b5 --- /dev/null +++ b/tokens/tests/chart.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, test } from "bun:test"; +import { oklchToRgb, parseOklch } from "../src/color"; +import { type Mode, scheme } from "../src/scheme"; + +/* + * The chart series are colours a person tells apart, drawn on a card. They were five grays of + * slate: the first was 1.5:1 on a light card, the last nearly black on a dark one, and every chart + * in the app was gray. These hold what a chart colour must be. + */ + +const SERIES = ["chart-1", "chart-2", "chart-3", "chart-4", "chart-5"] as const; +const MODES: Mode[] = ["light", "dark"]; + +/** sRGB channels, 0 to 1, linear. */ +function linear(color: string): [number, number, number] { + const { r, g, b } = oklchToRgb(color); + return [r, g, b].map((channel) => { + const v = channel / 255; + return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; + }) as [number, number, number]; +} + +/** WCAG 2 relative luminance and contrast ratio. */ +function luminance(color: string) { + const [r, g, b] = linear(color); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} +function contrast(a: string, b: string) { + const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return ((high as number) + 0.05) / ((low as number) + 0.05); +} + +/** Linear sRGB to OKLab. */ +function oklab([r, g, b]: number[]): number[] { + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return [ + 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, + 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, + 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s, + ]; +} + +/** + * Dichromat vision, as Machado, Oliveira and Fernandes (2009) model it at full severity, applied to + * linear sRGB. The same matrices colour-blindness simulators use. + */ +const VISION: Record = { + typical: null, + protanopia: [ + [0.152286, 1.052583, -0.204868], + [0.114503, 0.786281, 0.099216], + [-0.003882, -0.048116, 1.051998], + ], + deuteranopia: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], + tritanopia: [ + [1.255528, -0.076749, -0.178779], + [-0.078411, 0.930809, 0.147602], + [0.004733, 0.691367, 0.3039], + ], +}; + +function seen(color: string, matrix: number[][] | null) { + const rgb = linear(color); + const shown = matrix + ? matrix.map((row) => + Math.min( + 1, + Math.max(0, row[0] * rgb[0] + row[1] * rgb[1] + row[2] * rgb[2]), + ), + ) + : rgb; + return oklab(shown); +} + +describe("chart series colours", () => { + for (const mode of MODES) { + const palette = scheme[mode]; + + test(`${mode}: every series is at least 3:1 against the card`, () => { + const ratios = SERIES.map((token) => ({ + token, + enough: contrast(palette[token], palette.card) >= 3, + })); + expect(ratios).toEqual(SERIES.map((token) => ({ token, enough: true }))); + }); + + test(`${mode}: every series is clearly colourful, not a gray`, () => { + const chroma = SERIES.map((token) => ({ + token, + colourful: parseOklch(palette[token]).c >= 0.1, + })); + expect(chroma).toEqual( + SERIES.map((token) => ({ token, colourful: true })), + ); + }); + + test(`${mode}: the five stay apart in typical vision and for protan, deutan and tritan`, () => { + const closeTogether: string[] = []; + for (const [vision, matrix] of Object.entries(VISION)) { + const points = SERIES.map((token) => seen(palette[token], matrix)); + points.forEach((a, i) => { + points.slice(i + 1).forEach((b, offset) => { + // 0.08 in OKLab is about eight just-noticeable differences. + const apart = Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + if (apart < 0.08) + closeTogether.push( + `${vision}: ${SERIES[i]} and ${SERIES[i + offset + 1]}`, + ); + }); + }); + } + expect(closeTogether).toEqual([]); + }); + } +}); diff --git a/tokens/tests/slate.test.ts b/tokens/tests/slate.test.ts index bfb65150bc..8096894f56 100644 --- a/tokens/tests/slate.test.ts +++ b/tokens/tests/slate.test.ts @@ -11,7 +11,7 @@ function lch(value: string): [number, number, number] { /** * The grays: every color with a faint tint. White has none, and the accents (the ring, the * selected sidebar row, the empty pattern) and the status colors are far more saturated. The chart - * colors are Tailwind's slate already and are left as they are. + * colors are not grays at all; chart.test.ts holds them. */ function grays(mode: "light" | "dark") { return TOKENS.filter((token) => !token.startsWith("chart-")) From 55ecc9c2054ad4724da862114689d794eebb0c26 Mon Sep 17 00:00:00 2001 From: David McKay Date: Mon, 30 Nov 2026 15:39:47 -0800 Subject: [PATCH 014/224] Name generate_image's step in words: Making an image, Made an image (#2568) A Bot's generate_image step was drawn as "Generate image" wherever its card is not registered (inside a subtask, a run with no browser). It now reads like OpenBot's other tools, in words chosen for it, and says what was tried when it is blocked or doesn't work. --- app/tests/tool-name.test.ts | 7 +++++++ shared/tool-name.ts | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/app/tests/tool-name.test.ts b/app/tests/tool-name.test.ts index ea02f2baf0..91e4780f18 100644 --- a/app/tests/tool-name.test.ts +++ b/app/tests/tool-name.test.ts @@ -260,6 +260,13 @@ describe("this deployment's own tools", () => { }); }); + test("generate_image says it is making an image, then that it made one", () => { + expect(readToolName("generate_image", true)).toEqual({ + label: "Making an image", + }); + expect(readToolName("generate_image")).toEqual({ label: "Made an image" }); + }); + test("any other bare name reads in words, never as its identifier", () => { expect(readToolName("run_command", true)).toEqual({ label: "Run command" }); }); diff --git a/shared/tool-name.ts b/shared/tool-name.ts index d570e3b0eb..8c85959eb8 100644 --- a/shared/tool-name.ts +++ b/shared/tool-name.ts @@ -1,5 +1,6 @@ import { OFFER_CHECK_IN_TOOL } from "./check-in-offer"; import { SHOW_APP_ACCESS_TOOL } from "./connect-prompt"; +import { GENERATE_IMAGE_TOOL } from "./generate-image"; import { DELEGATE_TOOL, FOLLOW_UP_TOOL, @@ -881,6 +882,12 @@ const OWN_TOOLS: Record = { attempted: "Send a file", subject: "path", }, + [GENERATE_IMAGE_TOOL]: { + running: "Making an image", + done: "Made an image", + attempted: "Make an image", + failed: "Didn't make an image", + }, computer_run_command: { running: "Running a command", done: "Ran a command", From 99b2618f5711f7eb162814aa51b6686826bd40d5 Mon Sep 17 00:00:00 2001 From: Alexander Clarke Date: Mon, 30 Nov 2026 23:54:02 +0000 Subject: [PATCH 015/224] Count a connection from Desktop's first screen, and the engine setup measured (#2566) * Count a connection from Desktop's first screen, and the engine setup measured Signing in to OpenBot Cloud from Desktop's first screen sent nothing, and connecting to a company's OpenBot sent only that its screen was viewed. Both now send oss.desktop.openbot_connect, with sign_in's outcomes: the window says started when the person presses Sign in or Connect, and failed or cancelled with how long it took, from the one hook both ways share. The desktop says completed itself, since the window has gone to OpenBot by the time connect_to_openbot answers; the window hands it the screen and the time since the press. The screen (cloud or connect_openbot) and the outcome are closed enums; the address, its host and the sentence about what went wrong are never sent. Opening again with the sign-in the computer already has sends nothing, and a sign-in left behind when the screen goes says nothing when it ends. The first screen also shows on a later launch, for a sign-in that ended or a choice made again from Settings, and is counted there too. A connection never sends activated, so quitting after signing in to OpenBot Cloud was counted as setup_abandoned. A completed connection now ends the setup session the way activated does, without being activated; a quit after only started, or after failed, still counts. What the Account step's check measured of the engine was sent only inside setup_failed, for an engine too small. The desktop now sends it as oss.desktop.engine_measured, with the same closed Resources, once a launch and again only when the engine's CPUs or memory change, or the installation is new. A connection to an OpenBot elsewhere runs no engine here and never sends it. Both go through the closed schema and the same opt-out as every other Desktop event. The window may send openbot_connect's started, failed and cancelled, and neither completed nor engine_measured. Also fixes a doubled word in BusinessOpened's doc comment. * Prove Connect reads the screen and the wait by the names the window sends A completed openbot_connect is counted from the screen and waitedMs the first screen hands connect_to_openbot. Under any other name they would be dropped and nothing counted, with no error anywhere, so a test through the command's IPC now pins the names: a closed screen and a number are taken, anything else is refused as it arrives. TELEMETRY.md's setup_abandoned paragraph now says a completed connection ends setup too. --------- Co-authored-by: David McKay --- CHANGELOG.md | 7 + desktop/TELEMETRY.md | 8 +- desktop/src-tauri/src/connected_ipc_tests.rs | 37 +++ desktop/src-tauri/src/desktop_connected.rs | 9 + desktop/src-tauri/src/desktop_telemetry.rs | 246 ++++++++++++++++ desktop/src-tauri/src/local_eval.rs | 24 +- desktop/src-tauri/src/main.rs | 31 +- desktop/src-tauri/src/telemetry.rs | 286 ++++++++++++++++++- desktop/src/App.test.tsx | 177 +++++++++++- desktop/src/ConnectToOpenBot.tsx | 56 +++- desktop/src/Welcome.tsx | 2 + desktop/src/telemetry.ts | 17 +- 12 files changed, 865 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7ccb4096a..669b065168 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **OpenBot Desktop counts a connection from its first screen, and the engine setup measured.** + While you share usage data, signing in to OpenBot Cloud or connecting to your company's OpenBot + from the first screen says it started, then completed, failed or was cancelled, with how long it + took, and never the address. Quitting after such a connection no longer counts as setup + abandoned. Setup on this computer says once what it measured of the engine it + runs on (CPUs, memory and free disk against what setup needs), not only when the engine is too + small ([desktop/TELEMETRY.md](desktop/TELEMETRY.md)). - **New Bot lets you choose its default model.** A Bot that runs here can start on the model you pick when you make it, such as a design Bot on Claude Opus. Leave it alone and the Bot uses your default, as before. You can still change it later in the Bot's Setup. diff --git a/desktop/TELEMETRY.md b/desktop/TELEMETRY.md index 47b2da9773..926e1bdf05 100644 --- a/desktop/TELEMETRY.md +++ b/desktop/TELEMETRY.md @@ -51,6 +51,8 @@ All desktop event names begin with `oss.desktop.`. The Rust `EventData` enum and | `ui_stalled` | Setup step enum; seconds the window did not answer | | `business_opened` | Place enum (`welcome` or `move_to_cloud`) | | `business_booked` | Place enum (`welcome` or `move_to_cloud`) | +| `openbot_connect` | Screen enum (`cloud` or `connect_openbot`); outcome enum; optional milliseconds | +| `engine_measured` | Resources (booleans and numbers), as in `setup_failed` | For `model_chosen`, providers are `openai`, `anthropic`, `google`, `xai`, `compatible`, or `none`; credential paths are `subscription`, `api_key`, `oauth`, or `none`. OpenAI and Anthropic plan sign-ins use `subscription`. xAI's native sign-in uses its named provider with `oauth` (Google's did, before Gemini took an API key only); Google's and xAI's API-key routes use `compatible`, matching the picker’s endpoint choice. A compatible endpoint uses `api_key` only when a nonblank key is supplied or its saved key is explicitly selected; keyless endpoints use `none`. Skipping model setup uses provider and credential path `none`. `custom_base_url` records only whether a nonblank base URL was selected, never its value. @@ -62,12 +64,16 @@ For `model_chosen`, providers are `openai`, `anthropic`, `google`, `xai`, `compa `ui_stalled` is a setup window that stopped taking what the desktop sends it. While the setup, start or update screens show, the page invokes `setup_heartbeat` every five seconds, and as soon as a row's progress reaches it, with the highest progress number it has taken (`setup:progress` carries one). The heartbeat is never awaited and runs off the window's thread. Progress left untaken for over 30 seconds while the window is shown, not minimised and, on macOS, not covered is a stall. The Desktop log says `[ui] the window has not answered for 31s during start_machine` when it is noticed and `[ui] the window stopped answering for 42s during start_machine` when it ends, and that end sends one `ui_stalled` with `stalled_seconds` and `step`, the setup row the desktop was reporting, by the same names as `failing_step`. It ends when the page catches up, the window leaves the screen, the window loads another page, or OpenBot quits. A page that has just loaded counts what was sent before it listened as taken, and a page that sends no heartbeat (OpenBot itself) is not watched. -`setup_abandoned` is setup ending before activation: Quit during setup, or, on the next launch, a crash. `setup_restart_required` is setup ending for the Windows restart that turning on Windows Subsystem for Linux needs, at the step it was on: Restart now, or Windows ending the app while that restart is owed (a restart from the Start menu). It is saved before Windows ends the app and sent by the launch after the restart, which carries on the same setup under the same installation UUID; that exit is never a `setup_abandoned`. A Quit while the restart is owed is still `setup_abandoned`. +`setup_abandoned` is setup ending before activation, or before a connection from the first screen completed (`openbot_connect`): Quit during setup, or, on the next launch, a crash. `setup_restart_required` is setup ending for the Windows restart that turning on Windows Subsystem for Linux needs, at the step it was on: Restart now, or Windows ending the app while that restart is owed (a restart from the Start menu). It is saved before Windows ends the app and sent by the launch after the restart, which carries on the same setup under the same installation UUID; that exit is never a `setup_abandoned`. A Quit while the restart is owed is still `setup_abandoned`. `windows_probe` is one of the Windows readiness check's probes, which the setup window waits on before it shows its first screen, that ran long or was stopped at its limit. Sent by the desktop itself, once per such probe, on Windows only. `probe` is which one, by what it asks: `virtualization`, `administrator`, `wsl_feature`, `wsl_service`, `virtual_machine_platform_feature`, `wsl_version`, `wsl_system_start` (`wsl.exe --system`, which starts WSL's own VM) or `docker`. `outcome` is `slow` (it answered, after the probe's slow mark) or `timed_out` (it was stopped at its limit and counted as no answer). `duration_ms` is how long it ran. Slow marks are well under the limits: 5 seconds for the PowerShell probes and `wsl_version` (limit 30), 3 for `docker` (limit 10), and 20 for `wsl_system_start` (limit 60; a cold start measured about 6). A probe that answers in good time sends nothing. Never the command, its output, its error or a path. `business_opened` is OpenBot for Business's booker coming on screen because it was picked: on the first screen (`welcome`) or in Move to Cloud (`move_to_cloud`), once for each place each time the setup window's page loads (coming back to setup from OpenBot loads it again), however often it is picked again there. `business_booked` is a call booked in its calendar, said by Calendly from its own origin and the calendar's frame. The window sends both, with the place and nothing else: never the time booked or anything typed into the calendar. The calendar's address carries the same place as `utm_content` beside `utm_source=openbot_app` and `utm_medium=in_app`, which Calendly keeps on the booking, so a booking and these events name the same screen. +`openbot_connect` is the first screen's connection to an OpenBot that runs elsewhere, by the screen it was made on: OpenBot Cloud's sign-in (`cloud`) or a company's OpenBot by its address (`connect_openbot`). It counts that screen whenever it shows: on a first setup, and on a later launch that shows it again, such as a saved connection whose sign-in ended (Sign in again) or the choice of where OpenBot runs made again from Settings. The window sends `started` when the person presses Sign in, Connect, Try again or Sign in again, then `failed` when the address check or the browser sign-in fails, or `cancelled` when the person presses Cancel. The desktop itself sends `completed` once signed in and that OpenBot is shown, since the window has gone to it by then. Each ending has `duration_ms` from the press, and the outcomes are `sign_in`'s. A Cancel pressed just as the sign-in completes can give `cancelled` and then `completed` for one go: it did connect. `completed` also ends the setup session, as `activated` does for OpenBot on this computer, so a quit afterwards is not `setup_abandoned`; it is not `activated`, since nothing started here. Move to Cloud signs in its own way and never sends it. Opening a connection again with the sign-in this computer already has sends nothing, and a sign-in left behind when the screen goes says nothing when it ends. Never the address, its host or the sentence about what went wrong. It is not `sign_in`, which stays the Account step's CopilotKit sign-in. + +`engine_measured` is what the Account step's check measured of the engine local setup runs on, too small or not: `resources` as `setup_failed` carries it for an engine too small, CPUs in thousandths and memory and free disk in MiB, against what setup needs. Sent by the desktop itself, never by the window, once a launch and again only when the engine's CPUs or memory change (a Podman machine made bigger). Free disk is sent with them, but a change in it alone, as the downloads fill the disk, sends nothing new. Every install that goes through the Account step runs that check, so each one whose engine answers it sends one; an engine not known yet, or one that does not answer, is not measured and sends nothing, and neither does a reinstall that goes straight to Install. Nothing is kept while usage data is off, so turning it on again in the same launch still sends the size. OpenBot Cloud and a company's OpenBot run nothing on this computer, so a connection never sends it. Never the engine's name, a drive, a path or a hostname. + `sign_in` is the Account step's CopilotKit sign-in: `started`, then `completed`, `failed` or `cancelled` with how long it took, and `restored` once a launch when the account check finds this computer already signed in without a sign-in. Every event, the two stall events among them, carries desktop distribution, app version (numeric, with a release candidate's closed label such as `1.0.0-rc.5`), platform, architecture, numeric OS version when available, and engine. The runtime receives the same desktop metadata through its existing `telemetryProperties` hook, where the app version accepts only the same closed pre-release labels. No prompt, answer, credential, file name, path, hostname, email, model name, YAML value, or custom URL is accepted by the desktop schema. diff --git a/desktop/src-tauri/src/connected_ipc_tests.rs b/desktop/src-tauri/src/connected_ipc_tests.rs index 00faec6097..4e523a0ad5 100644 --- a/desktop/src-tauri/src/connected_ipc_tests.rs +++ b/desktop/src-tauri/src/connected_ipc_tests.rs @@ -249,6 +249,43 @@ mod connected_ipc { } } + /// The first screen hands Connect the screen it was pressed on and how long it has waited + /// (`useConnectToOpenBot` sends `screen` and `waitedMs`), and a connection that works is + /// counted `completed` from them. Under any other name they would be dropped and nothing + /// counted, so these are the names read: a screen that is not one of the two, or a time that + /// is not a number, is refused before anything is tried. + #[test] + fn connect_reads_the_screen_and_the_wait_by_the_names_the_window_sends() { + let shell = Connected::new(); + let connect = |args| shell.ask_with(SETUP, "connect_to_openbot", args); + // Taken: the blank address is what is refused, as the sentence the window shows. + for screen in ["cloud", "connect_openbot"] { + let answered = connect(serde_json::json!({ + "address": "", + "screen": screen, + "waitedMs": 400 + })); + assert!( + answered + .as_ref() + .is_err_and(|problem| problem.get("said").is_some()), + "{screen}: {answered:?}" + ); + } + // The window's own names are read: anything but a closed screen and a number in them is + // refused as it arrives. + for args in [ + serde_json::json!({ "address": "", "screen": "account_menu", "waitedMs": 400 }), + serde_json::json!({ "address": "", "screen": "cloud", "waitedMs": "400 ms" }), + ] { + let answered = connect(args.clone()); + assert!( + answered.as_ref().is_err_and(serde_json::Value::is_string), + "{args}: {answered:?}" + ); + } + } + /// OpenBot's page, served through the relay, may ask where it runs, sign out, change the /// connection and name the organisation. A page on another loopback port may not. #[test] diff --git a/desktop/src-tauri/src/desktop_connected.rs b/desktop/src-tauri/src/desktop_connected.rs index c710f77bd7..4a86f8474e 100644 --- a/desktop/src-tauri/src/desktop_connected.rs +++ b/desktop/src-tauri/src/desktop_connected.rs @@ -315,10 +315,16 @@ pub async fn check_openbot_address(address: String) -> Result /// Connect: check the address, sign in through the browser, start the relay and show OpenBot. /// The choice is kept only once all of that has worked. +/// +/// `screen` is the first screen's way that asked, and `waited_ms` how long since the person +/// pressed its button: a connection that works is counted `completed` here, in usage data, since +/// the window has moved on to OpenBot by the time this answers it. #[tauri::command] pub async fn connect_to_openbot( app: tauri::AppHandle, address: String, + screen: Option, + waited_ms: Option, ) -> Result<(), Problem> { let asked = std::time::Instant::now(); log::info!("[connect] asked"); @@ -329,6 +335,9 @@ pub async fn connect_to_openbot( let forward = app.clone(); let connected = blocking(move || connect_now(&app, &address, &opening)).await; openbot_desktop_lib::logging::outcome("connect", asked, &connected); + if let (Ok(()), Some(screen)) = (&connected, screen) { + crate::desktop_telemetry::connected(&forward, screen, waited_ms, asked.elapsed()); + } come_forward_after_sign_in( &forward, opened.load(std::sync::atomic::Ordering::SeqCst), diff --git a/desktop/src-tauri/src/desktop_telemetry.rs b/desktop/src-tauri/src/desktop_telemetry.rs index fe1aba1983..3432b256a3 100644 --- a/desktop/src-tauri/src/desktop_telemetry.rs +++ b/desktop/src-tauri/src/desktop_telemetry.rs @@ -21,6 +21,9 @@ pub struct DesktopTelemetry { account_refusal: Mutex>, /// A sign-in completed or an account was found signed in this launch: `restored` is said once. signed_in: AtomicBool, + /// The installation and the engine's CPUs and memory last said in `engine_measured`, so the + /// Account step's check, which the window asks again every few seconds, says one size once. + engine_size: Mutex>, } impl DesktopTelemetry { @@ -33,6 +36,7 @@ impl DesktopTelemetry { failures: AtomicU64::new(0), account_refusal: Mutex::new(None), signed_in: AtomicBool::new(false), + engine_size: Mutex::new(None), } } @@ -979,6 +983,82 @@ pub fn terms_failure( } } +/** +What the Account step's check measured of the engine, too small or not, as an `engine_measured`: +once a launch, and again only when its CPUs or memory change (a Podman machine made bigger). Free +disk is sent with the size, but a change in it alone, as the downloads fill the disk, sends nothing. +*/ +pub fn engine_measured( + app: &tauri::AppHandle, + measured: &local_eval::EngineMeasure, +) { + let Some(state) = app.try_state::() else { + return; + }; + // Not sharing usage data: nothing is kept. Turned on again, the installation is a new one, + // which is told the size afresh. + let Some(install_id) = state.emitter.install_id() else { + return; + }; + let Ok(mut last) = state.engine_size.lock() else { + return; + }; + if let Some(event) = engine_measured_event(&mut last, install_id, measured) { + drop(last); + record(app, event); + } +} + +/// The installation an engine size was said under, and the CPUs and memory said. +type EngineSize = (String, u64, u64); + +/// The `engine_measured` for `measured`, or None when its size was the last one said under this +/// installation. +fn engine_measured_event( + last: &mut Option, + install_id: String, + measured: &local_eval::EngineMeasure, +) -> Option { + let size = (install_id, measured.cpus, measured.memory_bytes); + if last.as_ref() == Some(&size) { + return None; + } + *last = Some(size); + let short = local_eval::engine_shortfall( + measured.cpus, + measured.memory_bytes, + measured.free_disk_bytes, + ); + Some(telemetry::EventData::EngineMeasured { + resources: resources_of_measure(short.cpu, short.memory, short.disk, measured), + }) +} + +/// A connection from the first screen worked (`desktop_connected::connect_to_openbot`): counted +/// here, since the window has moved on to OpenBot by the time the command answers it. +pub fn connected( + app: &tauri::AppHandle, + screen: telemetry::ConnectScreen, + waited_ms: Option, + took: std::time::Duration, +) { + record(app, connected_event(screen, waited_ms, took)); +} + +/// `completed`, with the time from the person's press: what the window had waited, and the sign-in. +fn connected_event( + screen: telemetry::ConnectScreen, + waited_ms: Option, + took: std::time::Duration, +) -> telemetry::EventData { + let took = u64::try_from(took.as_millis()).unwrap_or(u64::MAX); + telemetry::EventData::OpenbotConnect { + screen, + outcome: telemetry::ConnectOutcome::Completed, + duration_ms: Some(waited_ms.unwrap_or(0).saturating_add(took)), + } +} + /// The browser sign-in has started. pub fn sign_in_started(app: &tauri::AppHandle) { record( @@ -2284,6 +2364,172 @@ mod tests { ); } + /// The window says how a connection from the first screen went, by screen and outcome only. + /// It cannot say `completed`, which the desktop says itself, or what was measured of the + /// engine: only the desktop's own check does. + #[test] + fn connect_telemetry_ipc_accepts_a_screen_and_outcome_and_nothing_else() { + let fixture = Fixture::new(); + fixture.invoke(serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "started" + })); + fixture.invoke(serde_json::json!({ + "kind": "openbot_connect", + "screen": "connect_openbot", + "outcome": "failed", + "duration_ms": 9000 + })); + fixture.invoke(serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "cancelled", + "duration_ms": 3000 + })); + fixture.invoke(serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "completed", + "duration_ms": 9000 + })); + fixture.invoke(serde_json::json!({ + "kind": "openbot_connect", + "screen": "connect_openbot", + "outcome": "failed", + "address": "https://openbot.example.com" + })); + fixture.invoke(serde_json::json!({ + "kind": "engine_measured", + "resources": { + "cpu_short": false, "memory_short": false, "disk_short": false, + "cpu_needed_millis": 4000, "memory_needed_mib": 8192, "disk_needed_mib": 40960 + } + })); + + assert_eq!( + fixture.queued(), + vec![ + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::Cloud, + outcome: telemetry::ConnectOutcome::Started, + duration_ms: None, + }, + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::ConnectOpenbot, + outcome: telemetry::ConnectOutcome::Failed, + duration_ms: Some(9000), + }, + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::Cloud, + outcome: telemetry::ConnectOutcome::Cancelled, + duration_ms: Some(3000), + }, + ] + ); + } + + /// A connection that worked is counted by the desktop, with the time since the person pressed + /// the button: the window has moved on to OpenBot by then. + #[test] + fn a_connection_that_worked_is_counted_from_the_press() { + assert_eq!( + connected_event( + telemetry::ConnectScreen::Cloud, + Some(400), + std::time::Duration::from_millis(18_000), + ), + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::Cloud, + outcome: telemetry::ConnectOutcome::Completed, + duration_ms: Some(18_400), + } + ); + assert_eq!( + connected_event( + telemetry::ConnectScreen::ConnectOpenbot, + None, + std::time::Duration::from_millis(5), + ), + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::ConnectOpenbot, + outcome: telemetry::ConnectOutcome::Completed, + duration_ms: Some(5), + } + ); + assert_eq!( + connected_event( + telemetry::ConnectScreen::Cloud, + Some(u64::MAX), + std::time::Duration::from_millis(5), + ), + telemetry::EventData::OpenbotConnect { + screen: telemetry::ConnectScreen::Cloud, + outcome: telemetry::ConnectOutcome::Completed, + duration_ms: Some(u64::MAX), + } + ); + } + + /// The Account step's check runs every few seconds while it waits: one size is said once, a + /// new CPU count or memory (a Podman machine made bigger) or a new installation again, and + /// free disk alone never. + #[test] + fn engine_measured_says_each_size_once() { + let gib = 1024 * 1024 * 1024; + let measure = + |cpus: u64, memory_gib: u64, free_gib: Option| local_eval::EngineMeasure { + cpus, + memory_bytes: memory_gib * gib, + free_disk_bytes: free_gib.map(|free| free * gib), + }; + let mut last = None; + let install = || "install-a".to_string(); + let first = engine_measured_event(&mut last, install(), &measure(2, 4, Some(100))); + assert_eq!( + first, + Some(telemetry::EventData::EngineMeasured { + resources: telemetry::Resources { + cpu_short: local_eval::MIN_ENGINE_CPUS > 2, + memory_short: local_eval::MIN_ENGINE_MEMORY_BYTES > 4 * gib, + disk_short: local_eval::MIN_ENGINE_FREE_DISK_BYTES > 100 * gib, + disk_nearly_full: false, + cpu_needed_millis: local_eval::MIN_ENGINE_CPUS * 1000, + cpu_available_millis: Some(2000), + memory_needed_mib: local_eval::MIN_ENGINE_MEMORY_BYTES / MIB, + memory_available_mib: Some(4096), + disk_needed_mib: local_eval::MIN_ENGINE_FREE_DISK_BYTES / MIB, + disk_available_mib: Some(102_400), + }, + }) + ); + assert_eq!( + engine_measured_event(&mut last, install(), &measure(2, 4, Some(100))), + None + ); + assert_eq!( + engine_measured_event(&mut last, install(), &measure(2, 4, Some(60))), + None + ); + // Usage data turned off and on again: a new installation, told the same size afresh. + assert!( + engine_measured_event(&mut last, "install-b".into(), &measure(2, 4, Some(60))) + .is_some() + ); + let resized = engine_measured_event(&mut last, install(), &measure(8, 16, None)); + let Some(telemetry::EventData::EngineMeasured { resources }) = resized else { + panic!("a resized engine is not said again: {resized:?}"); + }; + assert_eq!(resources.cpu_available_millis, Some(8000)); + assert_eq!(resources.memory_available_mib, Some(16_384)); + assert_eq!(resources.disk_available_mib, None); + assert!(!resources.disk_short); + assert_eq!( + engine_measured_event(&mut last, install(), &measure(8, 16, None)), + None + ); + } + #[test] fn model_telemetry_ipc_accepts_provider_categories_without_private_properties() { let fixture = Fixture::new(); diff --git a/desktop/src-tauri/src/local_eval.rs b/desktop/src-tauri/src/local_eval.rs index d019f77813..79cf8b87fb 100644 --- a/desktop/src-tauri/src/local_eval.rs +++ b/desktop/src-tauri/src/local_eval.rs @@ -2011,10 +2011,21 @@ The onboarding check of the engine, before the account screen asks about the agr here; the CLI's own check still runs at Start. */ pub fn engine_size_terms() -> Option { + engine_size_terms_measured().and_then(|(_, terms)| terms) +} + +/// [`engine_size_terms`], with what it measured of the engine whenever it measured it, too small +/// or not (`desktop_telemetry::engine_measured`). Nothing when the engine's size is not known. +pub fn engine_size_terms_measured() -> Option<(EngineMeasure, Option)> { let address = cli_engine()?; let check = EngineCheck::of(&address); let (cpus, memory) = check.size?; let free = check.free_disk(); + let measured = EngineMeasure { + cpus, + memory_bytes: memory, + free_disk_bytes: free, + }; let short = engine_shortfall(cpus, memory, free); // While the person is asked to free space, the downloads behind the step hold, so they do not // fill the disk meanwhile: on Windows F free space went from 15.0 to 11.0 GB on this step. @@ -2024,10 +2035,10 @@ pub fn engine_size_terms() -> Option { crate::early_downloads::room_again(); } if !short.named() { - return None; + return Some((measured, None)); } log_check("before local setup", &check); - Some(Terms::EngineTooSmall { + let too_small = Terms::EngineTooSmall { podman: check.podman, cpu: short.cpu, memory: short.memory, @@ -2038,13 +2049,10 @@ pub fn engine_size_terms() -> Option { mac: short.disk && check.drive_named() && check.drive.as_ref().is_some_and(|drive| drive.mac), - measured: EngineMeasure { - cpus, - memory_bytes: memory, - free_disk_bytes: free, - }, + measured, drive: check.drive.and_then(|drive| drive.drive), - }) + }; + Some((measured, Some(too_small))) } /// The free disk the account step's check counts (`EngineCheck::free_disk`) on the engine the back diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 4d0a0c3c26..5fdf1cebb8 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -1934,7 +1934,14 @@ fn record_setup_event(app: tauri::AppHandle, event: serde_ | telemetry::EventData::HarnessChosen { .. } | telemetry::EventData::ModelChosen { .. } | telemetry::EventData::BusinessOpened { .. } - | telemetry::EventData::BusinessBooked { .. }), + | telemetry::EventData::BusinessBooked { .. } + // `completed` is the desktop's own to say (`desktop_connected::connect_to_openbot`). + | telemetry::EventData::OpenbotConnect { + outcome: telemetry::ConnectOutcome::Started + | telemetry::ConnectOutcome::Failed + | telemetry::ConnectOutcome::Cancelled, + .. + }), ) = serde_json::from_value(event) { desktop_telemetry::record(&app, event); @@ -11945,19 +11952,23 @@ async fn local_eval_terms( attempt: String, ) -> Result { let root = selected_root_or_default(&app); + let measuring = app.clone(); let result = tauri::async_runtime::spawn_blocking(move || { let asked = std::time::Instant::now(); // The CLI checks its engine before it answers. See `know_cli_engine`. know_cli_engine(&root); - // An engine too small for local setup is said here, before Start fails on it. - let terms = - account_terms( - own_machine_on_its_way(&root), - || match local_eval::engine_size_terms() { - Some(too_small) => Ok(too_small), - None => local_eval::terms_installed(&attempt), - }, - ); + // An engine too small for local setup is said here, before Start fails on it. What was + // measured of it, too small or not, goes in usage data. + let terms = account_terms(own_machine_on_its_way(&root), || { + let measured = local_eval::engine_size_terms_measured(); + if let Some((measure, _)) = &measured { + desktop_telemetry::engine_measured(&measuring, measure); + } + match measured.and_then(|(_, terms)| terms) { + Some(too_small) => Ok(too_small), + None => local_eval::terms_installed(&attempt), + } + }); // What the step waits on, said in the log when it changes. See `AccountWait`. let step = RUNNING_LOGGED .lock() diff --git a/desktop/src-tauri/src/telemetry.rs b/desktop/src-tauri/src/telemetry.rs index 0e16710d75..90c2b30581 100644 --- a/desktop/src-tauri/src/telemetry.rs +++ b/desktop/src-tauri/src/telemetry.rs @@ -484,6 +484,18 @@ impl Telemetry { .lock() .map_err(|_| TelemetryError::Poisoned)? = None; } + // A connection to an OpenBot that runs elsewhere ends setup on this computer: a quit + // afterwards is not `setup_abandoned`. Not `activated`, since nothing started here. + EventData::OpenbotConnect { + outcome: ConnectOutcome::Completed, + .. + } => { + state.last_step = None; + *self + .session_last_step_viewed + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; + } _ => { *self .session_last_step_viewed @@ -1212,8 +1224,8 @@ pub enum EventData { to_version: AppVersion, }, /// OpenBot for Business, with its booking calendar, came on screen because the person picked - /// it (`BusinessBooker`): on the first screen or in Move to Cloud. Said once for each each time - /// the setup window's page loads. + /// it (`BusinessBooker`): on the first screen or in Move to Cloud. Said once for each place each + /// time the setup window's page loads. BusinessOpened { place: BusinessPlace, }, @@ -1222,6 +1234,44 @@ pub enum EventData { BusinessBooked { place: BusinessPlace, }, + /// The first screen's connection to an OpenBot that runs elsewhere (`useConnectToOpenBot`), on + /// a first setup or when a later launch shows that screen again (a sign-in that ended, or a + /// choice made again from Settings): `started` when the person presses Sign in or Connect, then `completed`, `failed` or + /// `cancelled` with how long it took. Never the address or what went wrong. + OpenbotConnect { + screen: ConnectScreen, + outcome: ConnectOutcome, + #[serde(default, skip_serializing_if = "Option::is_none")] + duration_ms: Option, + }, + /// What the Account step's check measured of the engine local setup runs on, against what + /// setup needs (`desktop_telemetry::engine_measured`): once a launch, and again only when its + /// CPUs or memory change. Numbers and booleans only, never the engine's name or a drive. + EngineMeasured { + resources: Resources, + }, +} + +/// Which of the first screen's ways to an OpenBot that runs elsewhere a connection was made on. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ConnectScreen { + /// OpenBot Cloud's sign-in. + Cloud, + /// A company's OpenBot, by its address: the `connect_openbot` step. + ConnectOpenbot, +} + +/// How a connection from the first screen went. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ConnectOutcome { + Started, + /// Signed in: that OpenBot is shown in this window. + Completed, + Failed, + /// The person pressed Cancel while the browser was waited on. + Cancelled, } /// Where the setup window drew OpenBot for Business's booker, by the name its calendar is tagged @@ -1259,6 +1309,8 @@ impl EventData { Self::UpdateRestored { .. } => "oss.desktop.update_restored", Self::BusinessOpened { .. } => "oss.desktop.business_opened", Self::BusinessBooked { .. } => "oss.desktop.business_booked", + Self::OpenbotConnect { .. } => "oss.desktop.openbot_connect", + Self::EngineMeasured { .. } => "oss.desktop.engine_measured", } } } @@ -1839,6 +1891,13 @@ pub fn schema_json() -> serde_json::Value { "ask", "connect_openbot", ]; + // `Resources`, the same in `setup_failed` and `engine_measured`. + let resources = serde_json::json!({ + "cpu_short": "bool", "memory_short": "bool", "disk_short": "bool", "disk_nearly_full": "bool", + "cpu_needed_millis": "u64", "cpu_available_millis": "option_u64", + "memory_needed_mib": "u64", "memory_available_mib": "option_u64", + "disk_needed_mib": "u64", "disk_available_mib": "option_u64" + }); serde_json::json!({ "schema_version": STATE_SCHEMA_VERSION, "event_name_prefix": "oss.desktop.", @@ -1871,12 +1930,7 @@ pub fn schema_json() -> serde_json::Value { "failing_step": FAILING_STEPS, "cli_reason": CLI_REASONS, "cli_failure": CLI_FAILURES, - "resources": { - "cpu_short": "bool", "memory_short": "bool", "disk_short": "bool", "disk_nearly_full": "bool", - "cpu_needed_millis": "u64", "cpu_available_millis": "option_u64", - "memory_needed_mib": "u64", "memory_available_mib": "option_u64", - "disk_needed_mib": "u64", "disk_available_mib": "option_u64" - } + "resources": resources.clone() }, "activated": {}, "setup_abandoned": { "step": steps }, @@ -1917,7 +1971,13 @@ pub fn schema_json() -> serde_json::Value { "to_version": { "pattern": APP_VERSION_PATTERN } }, "business_opened": { "place": ["welcome", "move_to_cloud"] }, - "business_booked": { "place": ["welcome", "move_to_cloud"] } + "business_booked": { "place": ["welcome", "move_to_cloud"] }, + "openbot_connect": { + "screen": ["cloud", "connect_openbot"], + "outcome": ["started", "completed", "failed", "cancelled"], + "duration_ms": "option_u64" + }, + "engine_measured": { "resources": resources } }, // Sent beside the context on every event: the install id the event is sent under, which // the server's events carry as their own `deployment_id`. @@ -2320,6 +2380,161 @@ mod tests { ); } + /// The first screen's connection to an OpenBot elsewhere: a closed screen, a closed outcome and + /// how long it took, so no address, host or sentence about what went wrong can ride along. + #[test] + fn openbot_connect_carries_only_its_screen_outcome_and_time() { + for screen in ["cloud", "connect_openbot"] { + for outcome in ["started", "completed", "failed", "cancelled"] { + let sent = serde_json::json!({ + "kind": "openbot_connect", + "screen": screen, + "outcome": outcome + }); + let event = serde_json::from_value::(sent.clone()) + .expect("a connection event is refused"); + assert_eq!(event.event_name(), "oss.desktop.openbot_connect"); + assert_eq!(serde_json::to_value(&event).unwrap(), sent); + } + } + let timed = serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "completed", + "duration_ms": 18_400 + }); + assert_eq!( + serde_json::to_value(serde_json::from_value::(timed.clone()).unwrap()) + .unwrap(), + timed + ); + for refused in [ + serde_json::json!({ "kind": "openbot_connect", "screen": "account_menu", "outcome": "started" }), + serde_json::json!({ "kind": "openbot_connect", "screen": "cloud", "outcome": "connected" }), + serde_json::json!({ "kind": "openbot_connect", "screen": "cloud" }), + serde_json::json!({ + "kind": "openbot_connect", + "screen": "connect_openbot", + "outcome": "failed", + "address": "https://openbot.example.com" + }), + serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "completed", + "email": "someone@example.invalid" + }), + serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "completed", + "connected_at": "2026-11-30T22:00:00Z" + }), + serde_json::json!({ + "kind": "openbot_connect", + "screen": "cloud", + "outcome": "failed", + "duration_ms": "18 seconds" + }), + ] { + assert!(serde_json::from_value::(refused).is_err()); + } + assert_eq!( + schema_json()["events"]["openbot_connect"], + serde_json::json!({ + "screen": ["cloud", "connect_openbot"], + "outcome": ["started", "completed", "failed", "cancelled"], + "duration_ms": "option_u64" + }) + ); + } + + /// The engine as measured, against what setup needs: the closed `Resources` and nothing else, + /// so no engine name, drive, path or hostname can ride along. + #[test] + fn engine_measured_carries_only_resources() { + let sent = serde_json::json!({ + "kind": "engine_measured", + "resources": { + "cpu_short": false, + "memory_short": true, + "disk_short": false, + "cpu_needed_millis": 4000, + "cpu_available_millis": 8000, + "memory_needed_mib": 8192, + "memory_available_mib": 4096, + "disk_needed_mib": 40960, + "disk_available_mib": 120000 + } + }); + let event = serde_json::from_value::(sent.clone()).unwrap(); + assert_eq!(event.event_name(), "oss.desktop.engine_measured"); + assert_eq!(serde_json::to_value(&event).unwrap(), sent); + for (field, value) in [ + ("drive", serde_json::json!("C:\\Users\\someone")), + ("hostname", serde_json::json!("someones-macbook")), + ("engine", serde_json::json!("podman")), + ] { + let mut private = sent.clone(); + private["resources"][field] = value.clone(); + assert!(serde_json::from_value::(private).is_err()); + let mut beside = sent.clone(); + beside[field] = value; + assert!(serde_json::from_value::(beside).is_err()); + } + let mut worded = sent.clone(); + worded["resources"]["memory_available_mib"] = serde_json::json!("4 GB"); + assert!(serde_json::from_value::(worded).is_err()); + assert!(serde_json::from_value::( + serde_json::json!({ "kind": "engine_measured" }) + ) + .is_err()); + // One `Resources` schema, the same in both events. + assert_eq!( + schema_json()["events"]["engine_measured"]["resources"], + schema_json()["events"]["setup_failed"]["resources"] + ); + } + + /// With usage data off, neither new event is kept or sent. + #[test] + fn opt_out_keeps_no_connection_or_engine_event() { + let dir = temp_dir("connect-engine-opt-out"); + let telemetry = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + enabled("http://127.0.0.1:9/ingest".to_string()), + EnvOverride::Disabled, + ) + .unwrap(); + telemetry + .record(EventData::OpenbotConnect { + screen: ConnectScreen::Cloud, + outcome: ConnectOutcome::Completed, + duration_ms: Some(1), + }) + .unwrap(); + telemetry + .record(EventData::EngineMeasured { + resources: Resources { + cpu_short: false, + memory_short: false, + disk_short: false, + disk_nearly_full: false, + cpu_needed_millis: 4000, + cpu_available_millis: Some(8000), + memory_needed_mib: 8192, + memory_available_mib: Some(16384), + disk_needed_mib: 40960, + disk_available_mib: None, + }, + }) + .unwrap(); + telemetry.flush().unwrap(); + assert!(telemetry.install_id().is_none()); + assert!(!state_path(&dir).exists()); + } + #[test] fn event_schema_is_tagged_closed_and_exposes_centralized_name() { let event = Event::new( @@ -3114,6 +3329,59 @@ mod tests { .any(|event| matches!(event.data, EventData::SetupAbandoned { .. }))); } + /// Signed in to OpenBot Cloud from the first screen, then quit: setup ended with the + /// connection, so the quit is not an abandonment. A go that only started still is. + #[test] + fn a_completed_connection_ends_setup_so_a_quit_is_not_abandonment() { + for (outcomes, abandoned) in [ + ( + vec![ConnectOutcome::Started, ConnectOutcome::Completed], + false, + ), + (vec![ConnectOutcome::Started], true), + (vec![ConnectOutcome::Started, ConnectOutcome::Failed], true), + ] { + let dir = temp_dir("connect-then-quit"); + let telemetry = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + telemetry + .record(EventData::StepViewed { + step: Step::Welcome, + }) + .unwrap(); + for outcome in &outcomes { + telemetry + .record(EventData::OpenbotConnect { + screen: ConnectScreen::Cloud, + outcome: *outcome, + duration_ms: None, + }) + .unwrap(); + } + telemetry.shutdown().unwrap(); + let state = telemetry.snapshot().unwrap(); + assert_eq!( + state.queue.iter().any(|event| matches!( + event.data, + EventData::SetupAbandoned { + step: Step::Welcome + } + )), + abandoned, + "{outcomes:?}" + ); + assert!(!state + .queue + .iter() + .any(|event| matches!(event.data, EventData::Activated))); + } + } + #[test] fn quit_abandonment_is_not_duplicated_on_next_launch() { let dir = temp_dir("quit-reopen"); diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index b4c858a382..556b095b77 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -188,6 +188,33 @@ function setupEvents() { .map((call) => call.args); } +/** + * The first screen's connections to an OpenBot elsewhere, as counted: screen and outcome, and + * whether a time came with them (how long varies from run to run). + */ +function connectEvents() { + return setupEvents() + .map( + (call) => + (call as { event: Record }).event as { + kind: string; + screen?: string; + outcome?: string; + duration_ms?: unknown; + }, + ) + .filter((event) => event.kind === "openbot_connect") + .map(({ screen, outcome, duration_ms, ...rest }) => { + expect(rest).toEqual({ kind: "openbot_connect" }); + if (duration_ms !== undefined) { + expect(Number.isInteger(duration_ms) && Number(duration_ms) >= 0).toBe( + true, + ); + } + return { screen, outcome, timed: duration_ms !== undefined }; + }); +} + /** Install on the first screen, past the account step, to the AI provider screen. */ async function reachAi(view: Awaited>) { await installLocal(view); @@ -1426,12 +1453,24 @@ test("a good address signs in through the browser, and nothing on this computer command: "check_openbot_address", args: { address: "openbot.example.com" }, }, - { command: "connect_to_openbot", args: { address: ELSEWHERE } }, + { + command: "connect_to_openbot", + args: { + address: ELSEWHERE, + screen: "connect_openbot", + waitedMs: expect.any(Number), + }, + }, ]); // The screen is counted, and the address never is. expect(setupEvents()).toContainEqual({ event: { kind: "step_viewed", step: "connect_openbot" }, }); + // Started when Connect was pressed. Completed is the shell's to count, from the screen and the + // time it was handed above: this page has gone to OpenBot by the time the shell answers. + expect(connectEvents()).toEqual([ + { screen: "connect_openbot", outcome: "started", timed: false }, + ]); expect(JSON.stringify(setupEvents())).not.toContain("openbot.example.com"); }); @@ -1682,8 +1721,16 @@ test("a launch after the sign-in ended says so once, with the address filled in "check_openbot_address", "connect_to_openbot", ]); + // Sign in again is a new go at connecting: started, and still waiting on the browser. expect(setupEvents()).toEqual([ { event: { kind: "step_viewed", step: "connect_openbot" } }, + { + event: { + kind: "openbot_connect", + screen: "connect_openbot", + outcome: "started", + }, + }, ]); expect(strays).toEqual([]); }); @@ -2021,7 +2068,10 @@ describe("with OpenBot Cloud on in this build (VITE_OPENBOT_CLOUD_ENABLED=true)" await view.findByText("Finish signing in in your browser."); expect(asked(from)).toEqual([ { command: "check_openbot_address", args: { address: CLOUD } }, - { command: "connect_to_openbot", args: { address: CLOUD } }, + { + command: "connect_to_openbot", + args: { address: CLOUD, screen: "cloud", waitedMs: expect.any(Number) }, + }, ]); // While the browser is waited on, Cancel is the way out: the rows and the links hold still. expect( @@ -2078,6 +2128,121 @@ describe("with OpenBot Cloud on in this build (VITE_OPENBOT_CLOUD_ENABLED=true)" expect(checks).toBe(2); }); + /* + * Signing in to OpenBot Cloud from the first screen used to say nothing. Each go says it started + * when Sign in is pressed, then how it ended, by the screen and nothing else: never the address + * or the sentence about what went wrong. + */ + test("signing in to OpenBot Cloud is counted from the first screen: started, then failed, completed or cancelled", async () => { + setupRootConfiguration("/tmp/cloud-sign-in-counted", async () => + emptyConfiguration(), + ); + const said = + "OpenBot couldn't reach api.open.bot. Check the address and your network, then try again."; + let checks = 0; + const signIn = deferred(); + withLocalCli({ + connection: THIS_COMPUTER, + record_setup_event: null, + check_openbot_address: (args: { address: string }) => { + checks += 1; + if (checks === 1) throw { said, kind: "unreachable" }; + return { address: args.address }; + }, + connect_to_openbot: () => signIn.promise, + }); + const view = await renderApp(); + await userEvent.click( + view.getByRole("button", { name: "Sign in to OpenBot Cloud" }), + ); + expect((await view.findByRole("alert")).textContent).toBe(said); + expect(connectEvents()).toEqual([ + { screen: "cloud", outcome: "started", timed: false }, + { screen: "cloud", outcome: "failed", timed: true }, + ]); + await userEvent.click(view.getByRole("button", { name: "Try again" })); + await view.findByText("Finish signing in in your browser."); + await act(async () => signIn.resolve(null)); + await view.findByText("Opening OpenBot…"); + // Completed is the shell's to count: it is told which screen asked, and nothing else. + expect(connectEvents()).toEqual([ + { screen: "cloud", outcome: "started", timed: false }, + { screen: "cloud", outcome: "failed", timed: true }, + { screen: "cloud", outcome: "started", timed: false }, + ]); + const signIns = invokeCalls.filter( + (call) => call.command === "connect_to_openbot", + ); + expect(signIns.map((call) => call.args)).toEqual([ + { + address: "https://api.open.bot", + screen: "cloud", + waitedMs: expect.any(Number), + }, + ]); + expect(JSON.stringify(setupEvents())).not.toContain("open.bot"); + expect(JSON.stringify(setupEvents())).not.toContain("couldn't reach"); + }); + + test("a Cloud sign-in cancelled from the first screen is counted once as cancelled, and its end afterwards says nothing", async () => { + setupRootConfiguration("/tmp/cloud-sign-in-cancelled", async () => + emptyConfiguration(), + ); + const signIn = deferred(); + withLocalCli({ + connection: THIS_COMPUTER, + record_setup_event: null, + check_openbot_address: (args: { address: string }) => ({ + address: args.address, + }), + connect_to_openbot: () => signIn.promise, + cancel_connect: null, + }); + const view = await renderApp(); + await userEvent.click( + view.getByRole("button", { name: "Sign in to OpenBot Cloud" }), + ); + await view.findByText("Finish signing in in your browser."); + await userEvent.click(view.getByRole("button", { name: "Cancel" })); + // The browser's sign-in ends later, as the shell stops it: that go was cancelled already. + await act(async () => + signIn.reject({ said: "Cancelled.", kind: "sign-in-cancelled" }), + ); + expect(connectEvents()).toEqual([ + { screen: "cloud", outcome: "started", timed: false }, + { screen: "cloud", outcome: "cancelled", timed: true }, + ]); + }); + + test("a Cloud sign-in left behind when the screen goes says only that it started", async () => { + setupRootConfiguration("/tmp/cloud-sign-in-left", async () => + emptyConfiguration(), + ); + const signIn = deferred(); + withLocalCli({ + connection: THIS_COMPUTER, + record_setup_event: null, + check_openbot_address: (args: { address: string }) => ({ + address: args.address, + }), + connect_to_openbot: () => signIn.promise, + cancel_connect: null, + }); + const view = await renderApp(); + await userEvent.click( + view.getByRole("button", { name: "Sign in to OpenBot Cloud" }), + ); + await view.findByText("Finish signing in in your browser."); + view.unmount(); + await act(async () => + signIn.reject({ said: "Cancelled.", kind: "sign-in-cancelled" }), + ); + expect(invokeCalls.map((call) => call.command)).toContain("cancel_connect"); + expect(connectEvents()).toEqual([ + { screen: "cloud", outcome: "started", timed: false }, + ]); + }); + test("a build pointed at another OpenBot Cloud signs in there", async () => { const url = process.env.VITE_OPENBOT_CLOUD_URL; process.env.VITE_OPENBOT_CLOUD_URL = " https://cloud-test.example.com/ "; @@ -2189,7 +2354,11 @@ describe("with OpenBot Cloud on in this build (VITE_OPENBOT_CLOUD_ENABLED=true)" }, { command: "connect_to_openbot", - args: { address: "https://api.cloud-test.example.com" }, + args: { + address: "https://api.cloud-test.example.com", + screen: "cloud", + waitedMs: expect.any(Number), + }, }, ]); } finally { @@ -2363,6 +2532,8 @@ test("a saved sign-in that can't open OpenBot says why on the connect screen, an "show_connected", "show_connected", ]); + // Opened with the sign-in this computer had: not a go at connecting, so nothing is counted. + expect(connectEvents()).toEqual([]); expect(strays).toEqual([]); }); diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 74bd70e521..6b4bb37586 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -3,6 +3,7 @@ import { useEffect, useId, useRef, useState } from "react"; import { ExternalLink } from "./ExternalLink"; import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; +import { type ConnectScreen, recordSetupEvent } from "./telemetry"; import { APP_TOO_OLD, APP_TOO_OLD_SECURITY, @@ -64,12 +65,19 @@ export type Connecting = ReturnType; * connect to at the address, and gives it back as it understood it. `connect_to_openbot` opens the * browser, waits for the sign-in and then shows that OpenBot in this window. Nothing is installed * or started on this computer. + * + * `screen` names the screen in usage data: a go at connecting says `started` when the person + * presses the button, then `failed` or `cancelled` (their own Cancel) with how long it took. The + * shell says `completed`, with the time since the press, since this page has gone by then. + * Opening again with the sign-in this computer already has (`reopen`) says nothing, and a go left + * behind by leaving the screen says nothing when it ends. */ export function useConnectToOpenBot({ address: remembered = "", problem: found = null, reopen, onThisComputer, + screen, }: { /** The address connected to before, when there is one. */ address?: string; @@ -82,6 +90,8 @@ export function useConnectToOpenBot({ reopen?: () => Promise; /** Back to OpenBot on this computer. May fail, when a saved connection has to be switched. */ onThisComputer: () => void | Promise; + /** The screen this connection is made on, for usage data. */ + screen?: ConnectScreen; }) { const [address, setAddress] = useState(remembered); const [phase, setPhase] = useState("idle"); @@ -91,6 +101,8 @@ export function useConnectToOpenBot({ const [reopens, setReopens] = useState(Boolean(reopen)); // Each go at connecting: one that was cancelled or left behind says nothing when it ends. const attempt = useRef(0); + // When the go at connecting now under way was started, for usage data. Null once it has ended. + const startedAt = useRef(null); const waiting = useRef(false); const alive = useRef(true); const field = useRef(null); @@ -102,6 +114,22 @@ export function useConnectToOpenBot({ (focus.on === "field" ? field : action).current?.focus(); }, [focus]); + /** + * How the go at connecting ended, with how long it took. Said once for each go. `completed` is + * the shell's to say (`connect_to_openbot`). + */ + function ended(outcome: "failed" | "cancelled") { + const began = startedAt.current; + startedAt.current = null; + if (!screen || began === null) return; + recordSetupEvent({ + kind: "openbot_connect", + screen, + outcome, + duration_ms: Math.max(0, Math.round(Date.now() - began)), + }); + } + useEffect(() => { alive.current = true; return () => { @@ -127,6 +155,13 @@ export function useConnectToOpenBot({ await reopen(); return; } + startedAt.current = Date.now(); + if (screen) + recordSetupEvent({ + kind: "openbot_connect", + screen, + outcome: "started", + }); setPhase("checking"); const checked = await invoke<{ address: string }>( "check_openbot_address", @@ -136,14 +171,26 @@ export function useConnectToOpenBot({ setAddress(checked.address); setPhase("waiting"); waiting.current = true; - await invoke("connect_to_openbot", { address: checked.address }); + await invoke("connect_to_openbot", { + address: checked.address, + // The shell counts a connection that worked, since this page has gone to OpenBot by + // the time it answers: which screen asked, and how long since the button was pressed. + ...(screen && startedAt.current !== null + ? { + screen, + waitedMs: Math.max(0, Math.round(Date.now() - startedAt.current)), + } + : {}), + }); if (!current()) return; waiting.current = false; - // Signed in: the shell is showing that OpenBot in this window. + // Signed in: the shell is showing that OpenBot in this window, and has counted it. + startedAt.current = null; setPhase("opening"); } catch (error) { if (!current()) return; waiting.current = false; + ended("failed"); const problem = asProblem(error); const offer = offerFor(problem.kind); setTrouble({ problem, offer }); @@ -156,8 +203,11 @@ export function useConnectToOpenBot({ } } - /** Stops the sign-in the browser is waited on for. The person chose it, so nothing is said. */ + /** + * Stops the sign-in the browser is waited on for. The person chose it, so no problem is shown. + */ async function cancel() { + ended("cancelled"); attempt.current += 1; waiting.current = false; setPhase("idle"); diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx index 6daaea1339..20ec5621ce 100644 --- a/desktop/src/Welcome.tsx +++ b/desktop/src/Welcome.tsx @@ -171,11 +171,13 @@ export function Welcome({ const connecting = useConnectToOpenBot({ ...(savedIsCloud ? {} : saved), onThisComputer, + screen: "connect_openbot", }); const signingIn = useConnectToOpenBot({ address: cloud, ...(savedIsCloud ? { problem: saved?.problem, reopen: saved?.reopen } : {}), onThisComputer, + screen: "cloud", }); // OpenBot Cloud or OpenBot for Business picked: shown whatever the app holds as the choice. With // Cloud on, Cloud is picked to begin with, unless setup on this computer failed and says so. diff --git a/desktop/src/telemetry.ts b/desktop/src/telemetry.ts index 405a706f99..024255638c 100644 --- a/desktop/src/telemetry.ts +++ b/desktop/src/telemetry.ts @@ -54,7 +54,22 @@ export type SetupEvent = * calendar: where, and nothing else (`BusinessBooker`). */ | { kind: "business_opened"; place: DesktopBusinessPlace } - | { kind: "business_booked"; place: DesktopBusinessPlace }; + | { kind: "business_booked"; place: DesktopBusinessPlace } + /* + * The first screen's connection to an OpenBot that runs elsewhere, by the screen it was made on: + * OpenBot Cloud's sign-in (`cloud`) or a company's OpenBot by its address (`connect_openbot`). + * How it went and how long it took, and nothing else: never the address (`useConnectToOpenBot`). + */ + | { + kind: "openbot_connect"; + screen: ConnectScreen; + // `completed` is the shell's own to say (`connect_to_openbot`), and refused from here. + outcome: "started" | "failed" | "cancelled"; + duration_ms?: number; + }; + +/** The first screen's two ways to connect to an OpenBot that runs elsewhere. */ +export type ConnectScreen = "cloud" | "connect_openbot"; export function harnessChoiceEvent(id: string): SetupEvent | null { // Match values rather than indexing with an arbitrary string, including prototype keys. From 71be9a6e016a3dd818f3d6cbf1f0db142016d52b Mon Sep 17 00:00:00 2001 From: Dusty Date: Mon, 30 Nov 2026 16:17:58 -0800 Subject: [PATCH 016/224] Show a conversation at once when it is opened again (#2561) * Show a conversation at once when it is opened again Keep what each conversation showed in memory, and draw it while its history is read again. Switching back to a conversation no longer shows an empty transcript and then every message sliding in. * Keep nothing past a sign-out, and no turn still going Two things the kept conversations got wrong, found in review: - The conversation open at sign-out was kept anyway. Signing out empties the store, then goes to the sign-in screen, and that is what closes the conversation, which then kept itself into the emptied store. Switching organization went the same way. A conversation now keeps only into the store it opened in (`transcriptEra`). - A conversation left while its Bot was working was kept part way through the turn. Opened again, its command read "Run a command, interrupted" for over a second while it was still running, because nothing runs on that screen until the join catches up. A conversation closed while a turn is going is now not kept, and loads as before. Tests: the conversation open while everything kept is let go is not drawn from memory (channel-history-refresh, fails before). A real browser test, Chromium and WebKit, light and dark: back to a conversation, built-in Bot and connected AG-UI Bot, its messages are on screen before the history read answers and a message added on another device comes in after it; signed out and back, nothing is drawn before the read (fails before); a command running on another device reads as running in every frame after coming back, never interrupted (fails before). Added to CI's real-browser list. --------- Co-authored-by: David McKay --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 7 + app/src/components/channels/channel-chat.tsx | 91 ++- .../components/channels/chat-transcript.tsx | 10 +- .../components/channels/conversation-view.tsx | 7 + .../channels/transcript-messages.ts | 19 + app/src/lib/auth/mutations.ts | 3 + app/src/lib/copilot/active-bot.tsx | 14 + app/src/lib/copilot/kept-transcripts.ts | 113 +++ app/tests/channel-history-refresh.test.tsx | 84 +++ app/tests/conversation-kept-browser.test.tsx | 660 ++++++++++++++++++ app/tests/conversation-kept.fixture.tsx | 167 +++++ app/tests/kept-transcripts.test.ts | 124 ++++ app/tests/preload.ts | 9 + app/tests/transcript-messages.test.ts | 34 + 15 files changed, 1333 insertions(+), 11 deletions(-) create mode 100644 app/src/lib/copilot/kept-transcripts.ts create mode 100644 app/tests/conversation-kept-browser.test.tsx create mode 100644 app/tests/conversation-kept.fixture.tsx create mode 100644 app/tests/kept-transcripts.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 526fe0c9dd..2d23c9a3c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -494,7 +494,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx app/tests/stopped-command-layout.test.tsx + bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/conversation-kept-browser.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx app/tests/stopped-command-layout.test.tsx # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. - run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 669b065168..dfcaed6d89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **Going back to a conversation shows it at once.** Each click between conversations drew an + empty transcript, then every message sliding in again, while the conversation joined its thread + and read its history. The app now keeps what the conversations opened most recently showed (up + to 20, up to about 50 MB each and 100 MB in all), in memory only, and draws that while the + history is read behind it; what is new since comes in when it arrives. A conversation opened for + the first time since the page loaded, or left while its Bot was still working, loads as before. + Nothing kept is stored on the computer, and signing out or switching organization lets it go. - **OpenBot Desktop counts a connection from its first screen, and the engine setup measured.** While you share usage data, signing in to OpenBot Cloud or connecting to your company's OpenBot from the first screen says it started, then completed, failed or was cancelled, with how long it diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index e901ddc17f..df411800a8 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -42,6 +42,7 @@ import { } from "@/components/channels/stopped-connection-notice"; import { seedMessage, + shownTranscript, takeFirstMessage, transcriptMessages, } from "@/components/channels/transcript-messages"; @@ -84,7 +85,11 @@ import { } from "@/lib/channels/turns-finished-away"; import { publishedPlaygroundQueryOptions } from "@/lib/components/queries"; import { useConversationActivity } from "@/lib/computers/activity"; -import { channelAgentId, useActiveBot } from "@/lib/copilot/active-bot"; +import { + channelAgentId, + useActiveBot, + useActiveBotIs, +} from "@/lib/copilot/active-bot"; import { observeApprovalAgent, whileObserved, @@ -104,6 +109,11 @@ import { } from "@/lib/copilot/carried-turn"; import { ConversationProvider } from "@/lib/copilot/conversation"; import { afterMs, joinWithin } from "@/lib/copilot/join-thread"; +import { + keepTranscript, + keptTranscript, + transcriptEra, +} from "@/lib/copilot/kept-transcripts"; import { askRunEnding, askRunGoing, @@ -754,6 +764,15 @@ export function ChannelChat({ const fresh = first !== null; const firstOfFresh = useRef(fresh); + /** + * What this conversation showed the last time it was open, drawn while its history is read again + * (`lib/copilot/kept-transcripts.ts`). Taken once per mount. None for a conversation just started + * from the compose screen: it has no history, and its first message is already drawn. + */ + const [kept] = useState(() => + seed === null ? keptTranscript(channel.threadId) : null, + ); + /** Cleared by the send-on-mount effect without restarting it. */ const seedRef = useRef(first); @@ -1528,6 +1547,8 @@ export function ChannelChat({ // Tool calls from this conversation act on this coworker's own computer. useActiveBot(runtimeAgentId); + // The calls in what was kept are drawn for this Bot only once it is the one declared (`useActiveBotIs`). + const declared = useActiveBotIs(runtimeAgentId); // And what they did there is what the Activity pane beside its screen lists, whichever way they ran. useConversationActivity(runtimeAgentId, agent.messages); @@ -1566,6 +1587,36 @@ export function ChannelChat({ voicePending: voiceArchive.pending, voiceWaitedOut, }); + + /* + * Kept on leaving, for the next time it is opened: what the agent holds once its history is in. + * Not when the history never came in (still loading, unavailable, or only the stored copy drawn over + * a replay still going): what the agent holds then is part of the conversation, and the picture + * kept before is the better one. + */ + const historyInRef = useRef(false); + historyInRef.current = + !historyLoading && earlyHistory === null && historyAvailability === "ready"; + /* + * NOT WHILE ITS BOT IS WORKING. What is on screen of a turn still going is part way, and drawn + * again from memory nothing would be running on that screen yet: a command still running on the + * computer read "Run a command, interrupted" until the join caught up with the turn. Such a + * conversation loads as one never kept, and what was kept before it is let go. + */ + const workingRef = useRef(false); + useEffect(() => { + const threadId = channel.threadId; + // Into the store it opened in: signing out empties it before this conversation closes. + const openedIn = transcriptEra(); + return () => { + if (!historyInRef.current) return; + keepTranscript( + threadId, + workingRef.current ? [] : agentRef.current.messages, + openedIn, + ); + }; + }, [channel.threadId]); // While the connection line shows, it says why the history is missing; this does not repeat it. const historyNotice = connection.lost ? null @@ -2748,10 +2799,30 @@ export function ChannelChat({ * running, so what is typed meanwhile is queued, and a turn waits for the join gate. */ const earlyShown = earlyHistory !== null; - // Every render, as the transcript's messages always were: the agent's list changes in place. + /* + * Every render, as the transcript's messages always were: the agent's list changes in place. The + * stored history while the join replays it, which empties the agent (see `earlyHistory`), and + * before even that read is in, what was kept from the last time this conversation was open. + */ + const shown = shownTranscript({ + live: earlyShown ? earlyHistory : agent.messages, + kept: declared ? kept : null, + loading: historyLoading, + }); + /** + * A copy is on screen, not the agent's messages: the stored history the join is replaying, or what + * was kept from last time. Either is drawn as described above, with nothing in it that adds a turn. + */ + const copyShown = earlyShown || shown.fromKept; + // A turn going, as `pending` below counts one: what is on screen is not kept on leaving. + workingRef.current = + agent.isRunning || + turnsInFlight > 0 || + turnsAway > 0 || + carryingOn || + carriedByServer; const refused = withRefusedTurns( - // The stored history while the join replays it, which empties the agent: see `earlyHistory`. - transcriptMessages(earlyShown ? earlyHistory : agent.messages, seed), + transcriptMessages(shown.messages, seed), storedRefusals ?? [], ); for (const [messageId, sentence] of refusals) @@ -2764,7 +2835,7 @@ export function ChannelChat({ agentId={localAgentId} threadId={channel.threadId} > - +
    @@ -2882,7 +2953,7 @@ export function ChannelChat({ { setRunsInFlight((count) => count + 1); try { @@ -2987,7 +3058,9 @@ export function ChannelChat({ * above. */ queueWhileBusy - restoring={historyLoading} + // Not while what was kept from last time is up: that is a transcript, drawn as one. + restoring={historyLoading && !shown.fromKept} + kept={shown.fromKept} /* * Read-only, because one place that stops every renderer from acting on the stored copy * is safer than guarding each one: an A2UI surface's button sends its press straight to @@ -2995,7 +3068,7 @@ export function ChannelChat({ * has not confirmed. Only the stored copy's rows: what is queued meanwhile can still be * taken back. This lasts at most until the join ends or a live turn takes the screen. */ - readOnly={earlyShown} + readOnly={copyShown} /* * The run, not the turn. Stop reaches a run through the core's abort controller, and that * controller does not exist until `say` has finished waiting for the runtime agent — so diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index 63e2a87a99..6873019dc4 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -244,6 +244,11 @@ type ChatTranscriptProps = { * stay live. See `holdPress` for how, and `ChannelChat` for why. */ readOnly?: boolean; + /** + * The rows are what this conversation showed the last time it was open (`kept-transcripts.ts`). + * Already the conversation on screen, so they do not slide in as a conversation opened afresh does. + */ + kept?: boolean; /** * Why the last turn ended without an answer, if it did. * @@ -2437,6 +2442,7 @@ export function ChatTranscript({ queued = EMPTY_QUEUE, restoring = false, readOnly = false, + kept = false, stopped, refusals = NO_REFUSALS, stoppedNotice, @@ -2650,7 +2656,9 @@ export function ChatTranscript({ if (restoring) { openingRef.current = null; } else if (openingRef.current === null) { - openingRef.current = openingStagger(items.map((item) => item.id)); + openingRef.current = kept + ? new Map() + : openingStagger(items.map((item) => item.id)); } const opening = openingRef.current; const openingProps = (id: string) => { diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsx index 87dcbff207..5e140f4d2b 100644 --- a/app/src/components/channels/conversation-view.tsx +++ b/app/src/components/channels/conversation-view.tsx @@ -63,6 +63,7 @@ export function ConversationView({ queueWhileBusy = false, restoring = false, readOnly = false, + kept = false, intro, starterSuggestions, onSubmit, @@ -151,6 +152,11 @@ export function ConversationView({ * `ChatTranscript`. */ readOnly?: boolean; + /** + * The messages are what this conversation showed the last time it was open, drawn while its history + * is read again (`lib/copilot/kept-transcripts.ts`). They do not slide in; see `ChatTranscript`. + */ + kept?: boolean; /** * The top of the conversation, drawn above the first message and scrolled away with it. Only * where Bots are orbs (`useBotLook`); elsewhere the transcript starts at its first message. @@ -568,6 +574,7 @@ export function ConversationView({ queued={queued} restoring={restoring} readOnly={readOnly} + kept={kept} {...(stopped ? { stopped } : {})} {...(refusals ? { refusals } : {})} {...((stopped || refusals) && stoppedNotice ? { stoppedNotice } : {})} diff --git a/app/src/components/channels/transcript-messages.ts b/app/src/components/channels/transcript-messages.ts index 7a7906fcad..86de0a03df 100644 --- a/app/src/components/channels/transcript-messages.ts +++ b/app/src/components/channels/transcript-messages.ts @@ -69,3 +69,22 @@ export function takeFirstMessage(channelId: string): FirstMessage | null { firstMessages.delete(channelId); return message; } + +/** + * What the transcript draws: the agent's messages, or, while a conversation opened again still + * reads its history, what it showed the last time it was open (`lib/copilot/kept-transcripts.ts`). + * `fromKept` is whether that picture is up, which is not a loading transcript. + */ +export function shownTranscript({ + live, + kept, + loading, +}: { + live: readonly Message[]; + kept: readonly Message[] | null; + loading: boolean; +}): { messages: readonly Message[]; fromKept: boolean } { + return loading && kept !== null + ? { messages: kept, fromKept: true } + : { messages: live, fromKept: false }; +} diff --git a/app/src/lib/auth/mutations.ts b/app/src/lib/auth/mutations.ts index 6288184493..2a62e34624 100644 --- a/app/src/lib/auth/mutations.ts +++ b/app/src/lib/auth/mutations.ts @@ -1,6 +1,7 @@ import { mutationOptions, type QueryClient } from "@tanstack/react-query"; import { updatePerson } from "@/lib/api/generated/people/people"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { forgetTranscripts } from "@/lib/copilot/kept-transcripts"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { desktopConnectionQueryOptions, @@ -110,6 +111,8 @@ export function signOutMutationOptions(queryClient: QueryClient) { onSuccess: () => { clearSkin(); forgetSignedIn(); + // What was on screen of each conversation, kept in memory, goes with the person. + forgetTranscripts(); queryClient.removeQueries({ queryKey: authKeys.all }); }, }); diff --git a/app/src/lib/copilot/active-bot.tsx b/app/src/lib/copilot/active-bot.tsx index d47ad94445..7414a8e6b0 100644 --- a/app/src/lib/copilot/active-bot.tsx +++ b/app/src/lib/copilot/active-bot.tsx @@ -158,6 +158,20 @@ export function useActiveBotId(): string { return useContext(ActiveBotValueContext)?.botId ?? DEFAULT_BOT_ID; } +/** + * Whether a renderer reading the holder now finds `botId`. True where no provider holds one. + * + * A surface declares its Bot in an effect (`useActiveBot`), after its first render, and a renderer + * reads the holder while it renders. So a call drawn in a surface's very first render was drawn for + * the Bot before it: the help card on a conversation opened again watched the placeholder's + * computer, and offered Take control to the person who held it. Announced after the holder is set, + * so once this is true the holder says `botId` too. + */ +export function useActiveBotIs(botId: string): boolean { + const value = useContext(ActiveBotValueContext); + return value === null || value.botId === botId; +} + /** * The active Bot when a surface has declared one, and undefined while the placeholder holds. * diff --git a/app/src/lib/copilot/kept-transcripts.ts b/app/src/lib/copilot/kept-transcripts.ts new file mode 100644 index 0000000000..d856f074e3 --- /dev/null +++ b/app/src/lib/copilot/kept-transcripts.ts @@ -0,0 +1,113 @@ +import type { Message } from "@ag-ui/core"; +import { onOrganizationChange } from "@/lib/organizations/current"; + +/** + * The conversations kept in memory, so going back to one shows it at once. + * + * A conversation is drawn again from nothing each time somebody opens it: a new agent, a join of the + * thread, then a read of its whole history, one after the other. Clicking between two conversations + * showed an empty transcript, then every message sliding in again. What was on screen the last time + * is kept here and drawn while that happens, and the history read replaces it when it comes in. + * + * ONLY A PICTURE, NEVER THE RECORD. Nothing kept here is sent anywhere or handed to the agent: the + * join and the read still run on every visit, and what they bring is what the conversation holds. + * What is kept can be a few seconds behind, for as long as that read takes. + * + * In memory only, for this page: a reload starts with nothing kept, and nothing of a conversation is + * left on the computer. Signing out or working in another organization lets it all go. + */ + +/** How many conversations are kept. Opening one more lets go of the one opened longest ago. */ +export const KEPT_TRANSCRIPTS = 20; + +/** + * A conversation larger than this, measured as the characters of its JSON, is not kept: about 50 MB. + * Size comes from tool calls and their results, not from words: a conversation of 2,200 messages + * with a few kilobytes per tool result is already 7 MB, and those long, tool-heavy conversations + * are the slowest to load, so the ones most worth keeping. Measuring one this size takes about + * 15 ms. Larger loads as it did before. + */ +export const KEPT_TRANSCRIPT_MAX_CHARACTERS = 50_000_000; + +/** + * Every kept conversation together stays under this, measured the same way: about 100 MB. A tab + * full of large conversations lets the ones opened longest ago go, so what is kept never grows past + * this however many are opened. Many small ones all fit; a few large ones take turns. + */ +export const KEPT_TRANSCRIPTS_MAX_CHARACTERS = 100_000_000; + +/** + * By thread id, the conversation opened longest ago first (a Map keeps the order of insertion), with + * the size it was measured at. + */ +const kept = new Map< + string, + { messages: readonly Message[]; characters: number } +>(); +let keptCharacters = 0; + +/** + * Which sign-in and organization the store is for: a new one each time it is all let go. A + * conversation keeps on closing, and closing comes after the let-go that caused it (signing out + * goes to the sign-in screen once the store is empty; a new organization's frame replaces the old + * one after the change), so a conversation keeps only into the store it was opened in. + */ +let era = 0; + +/** The store's current era, read by a conversation as it opens and handed back as it closes. */ +export function transcriptEra(): number { + return era; +} + +function letGo(threadId: string): void { + const entry = kept.get(threadId); + if (entry === undefined) return; + kept.delete(threadId); + keptCharacters -= entry.characters; +} + +/** + * Keep what the conversation in `threadId` shows now. An empty transcript, or one too large, is not + * kept, and forgets what was kept before, so an old picture never outlives a newer one. Nothing is + * kept when everything has been let go since `openedIn` (see `era`). + */ +export function keepTranscript( + threadId: string, + messages: readonly Message[], + openedIn: number = era, +): void { + if (openedIn !== era) return; + letGo(threadId); + if (messages.length === 0) return; + const characters = JSON.stringify(messages).length; + if (characters > KEPT_TRANSCRIPT_MAX_CHARACTERS) return; + kept.set(threadId, { messages: [...messages], characters }); + keptCharacters += characters; + for (const oldest of kept.keys()) { + if ( + kept.size <= KEPT_TRANSCRIPTS && + keptCharacters <= KEPT_TRANSCRIPTS_MAX_CHARACTERS + ) + break; + letGo(oldest); + } +} + +/** What was kept for `threadId`, or null. Asking counts as opening it, so it is kept longest. */ +export function keptTranscript(threadId: string): readonly Message[] | null { + const entry = kept.get(threadId); + if (entry === undefined) return null; + kept.delete(threadId); + kept.set(threadId, entry); + return entry.messages; +} + +/** Let every kept conversation go, and any still open with them: on signing out. */ +export function forgetTranscripts(): void { + kept.clear(); + keptCharacters = 0; + era += 1; +} + +// Conversations belong to an organization; none is kept across a change of the one worked in. +onOrganizationChange(() => forgetTranscripts()); diff --git a/app/tests/channel-history-refresh.test.tsx b/app/tests/channel-history-refresh.test.tsx index bce753e8fb..a42d7d65ae 100644 --- a/app/tests/channel-history-refresh.test.tsx +++ b/app/tests/channel-history-refresh.test.tsx @@ -17,6 +17,7 @@ import { } from "@/lib/channels/queries"; import { applyChannelEvent } from "@/lib/channels/use-channel-events"; import { generativeUiProviderOptions, OPENBOT_UI } from "@/lib/copilot/a2ui"; +import { forgetTranscripts } from "@/lib/copilot/kept-transcripts"; import { queryClient } from "@/query-client"; import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; @@ -1475,3 +1476,86 @@ test.each(["mount", "refresh"])( expect(currentAgent().messages).toEqual([initial, local, fresh]); }, ); + +/** Whether a click on `element` is held back, as the transcript's read-only rows hold it. */ +function pressHeld(element: Element): boolean { + const click = new MouseEvent("click", { bubbles: true, cancelable: true }); + element.dispatchEvent(click); + return click.defaultPrevented; +} + +/** + * Going back to a conversation shows it at once. It used to be drawn from nothing each time: an empty + * transcript while the join and the history read ran one after the other, then every message sliding + * in again. What it showed the last time stays on screen while that happens, and the history read, + * which still runs, brings in what is new. + */ +test("a conversation opened again shows what it showed last time before its history answers", async () => { + const first = await mounted(); + first.unmount(); + + let answer: (response: Response) => void = () => {}; + const view = mounting( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + + // The history read has not answered: this is what was kept. + const kept = await view.findByText("Stored opening"); + // Seen, not used: a press on it would act on a conversation the agent has not restored yet. + expect(pressHeld(kept)).toBe(true); + // Already the conversation on screen, so it does not slide in as a conversation opened afresh does. + expect(kept.closest(".history-arrive")).toBeNull(); + + await act(async () => answer(stored([initial, fresh]))); + expect(await view.findByText("Fresh stored reply")).toBeTruthy(); + expect(pressHeld(view.getByText("Stored opening"))).toBe(false); +}); + +test("a conversation never opened shows nothing of its history before the history answers", async () => { + let answer: (response: Response) => void = () => {}; + const view = mounting( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + await waitFor(() => expect(historyReads).toEqual([channel.threadId])); + + expect(view.queryByText("Stored opening")).toBeNull(); + + await act(async () => answer(stored([initial]))); + const opened = await view.findByText("Stored opening"); + // Opened afresh, its history slides in (the contrast to the test above). + expect(opened.closest(".history-arrive")).not.toBeNull(); +}); + +/* + * THE CONVERSATION OPEN AT SIGN-OUT IS NOT KEPT EITHER. Signing out lets every kept conversation go + * (`signOutMutationOptions`), and only then goes to the sign-in screen, which is what closes the + * conversation on screen. It was kept as it closed, after the store had been emptied, so the next + * person in this page found it drawn on opening it. Switching organization goes the same way: the + * store is emptied as the organization changes, and the conversation closes after. + */ +test("a conversation open while everything kept is let go is not kept as it closes", async () => { + const first = await mounted(); + // As signing out, or a change of organization, does while the conversation is still on screen. + forgetTranscripts(); + first.unmount(); + + let answer: (response: Response) => void = () => {}; + const view = mounting( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + await waitFor(() => expect(historyReads).toEqual([channel.threadId])); + + expect(view.queryByText("Stored opening")).toBeNull(); + + await act(async () => answer(stored([initial]))); + expect(await view.findByText("Stored opening")).toBeTruthy(); +}); diff --git a/app/tests/conversation-kept-browser.test.tsx b/app/tests/conversation-kept-browser.test.tsx new file mode 100644 index 0000000000..57f5ffc145 --- /dev/null +++ b/app/tests/conversation-kept-browser.test.tsx @@ -0,0 +1,660 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { personBody } from "./accounts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { test } from "./renderer-crash"; + +/** + * Going back to a conversation draws it at once, in a real browser, and then shows what the server + * holds now. + * + * Each conversation is drawn from nothing when it is opened: its thread is joined and its history + * read, and until that read answers there was nothing on screen. The app now keeps what each + * conversation showed (src/lib/copilot/kept-transcripts.ts), in memory for this page, and draws it + * while the history is read again. This proves, with the real sidebar and the real conversation: + * + * - back in a conversation, its messages are on screen before its history read answers, and a + * message added since on another device comes in once it does, for a built-in Bot and a Bot + * connected over AG-UI alike; + * - signed out with a conversation open, and back, nothing of it is kept: it loads as a + * conversation never opened; + * - a Bot still running a command on another device reads as running when its conversation is + * opened again, never as interrupted. + * + * The history read is held back here, as a hosted read of a long thread is, so what is on screen + * before it answers is plain. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/conversation-kept-browser.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= each step is saved as conversation-kept---.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const origin = () => `http://127.0.0.1:${port}`; +const ORGANIZATION = "/api/v2/organizations/default"; + +/** How long a history read takes to answer: long enough that what shows before it is plain. */ +const READ_MS = 2_500; +/** Back in a conversation, what was kept is on screen within this. */ +const AT_ONCE_MS = 700; + +const PLAN_THREAD = "plan-thread"; +const NOTES_THREAD = "notes-thread"; +const WORK_THREAD = "work-thread"; + +const PLAN_QUESTION = "What is the plan for the launch?"; +const PLAN_ANSWER = "The plan has three steps: write, review, ship."; +const PLAN_ADDED = "Added on another device: ship on Friday."; +const NOTES_QUESTION = "Notes from the meeting?"; +const NOTES_ANSWER = "Here are the notes from today."; +const NOTES_ADDED = "Added on another device: the budget is approved."; +const WORK_QUESTION = "Run the tests, please."; +const WORK_COMMAND = "npm test"; + +/** What the store holds of each thread, and what was added to it on another device since. */ +const added = { plan: false, notes: false }; +function storedMessages(threadId: string): unknown[] { + if (threadId === PLAN_THREAD) + return [ + { id: "plan-asked", role: "user", content: PLAN_QUESTION }, + { id: "plan-answer", role: "assistant", content: PLAN_ANSWER }, + ...(added.plan + ? [{ id: "plan-added", role: "assistant", content: PLAN_ADDED }] + : []), + ]; + if (threadId === NOTES_THREAD) + return [ + { id: "notes-asked", role: "user", content: NOTES_QUESTION }, + { id: "notes-answer", role: "assistant", content: NOTES_ANSWER }, + ...(added.notes + ? [{ id: "notes-added", role: "assistant", content: NOTES_ADDED }] + : []), + ]; + return [ + { id: "work-asked", role: "user", content: WORK_QUESTION }, + { + id: "work-answer", + role: "assistant", + content: "", + toolCalls: [ + { + id: "work-command", + type: "function", + function: { + name: "computer_run_command", + arguments: JSON.stringify({ command: WORK_COMMAND }), + }, + }, + ], + }, + ]; +} +/** How many history reads each thread has had in the current test. */ +const reads = new Map(); + +const BOT = { + ...getGetBotResponseMock().bot, + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, + hidden: false, +}; +/** A Bot that runs inside OpenBot. */ +const PLAN_BOT = { + ...BOT, + id: "plan-bot", + name: "Plan Bot", + builtIn: true, + runsOnOpenBotModel: true, + endpoint: null, + framework: "OpenBot", +}; +/** A Bot connected over AG-UI, at an address of its own. */ +const NOTES_BOT = { + ...BOT, + id: "notes-bot", + name: "Notes Bot", + builtIn: false, + runsOnOpenBotModel: false, + endpoint: "https://agents.example/notes", + framework: "LangChain", +}; +const WORK_BOT = { ...PLAN_BOT, id: "work-bot", name: "Work Bot" }; +const BOTS = [PLAN_BOT, NOTES_BOT, WORK_BOT]; + +let port = 0; +let server: ReturnType | undefined; + +const sleep = (milliseconds: number) => + new Promise((resolve) => setTimeout(resolve, milliseconds)); + +/** The thread a Bot's conversation holds, by the Bot. */ +function threadOfBot(botId: string): string { + if (botId === "plan-bot") return PLAN_THREAD; + if (botId === "notes-bot") return NOTES_THREAD; + return WORK_THREAD; +} + +function threadOfConversation(conversationId: string): string { + return threadOfBot(conversationId.replace("-conversation", "-bot")); +} + +/** What the server answers: a status and a body, or nothing for an address it does not have. */ +function answer( + path: string, + method: string, +): { status?: number; json?: unknown } | undefined { + if (path === "/api/copilotkit/info") + return { + json: { + version: "fixture", + agents: Object.fromEntries( + BOTS.map((bot) => [ + bot.id, + { description: "Fixture", capabilities: {} }, + ]), + ), + mode: "intelligence", + intelligence: { wsUrl: `ws://127.0.0.1:${port}/client` }, + telemetryDisabled: true, + }, + }; + const connect = path.match(/\/agent\/([^/]+)\/connect$/); + if (connect) { + const threadId = threadOfBot(connect[1] ?? ""); + return { + json: { + threadId, + runId: null, + joinToken: "join-token", + realtime: { + clientUrl: `ws://127.0.0.1:${port}/client`, + topic: `thread:${threadId}`, + }, + }, + }; + } + const joinToken = path.match(/\/conversations\/([^/]+)\/join-tokens$/); + if (joinToken) { + const threadId = threadOfConversation(joinToken[1] ?? ""); + return { + status: 201, + json: { + joinToken: "join-token", + expiresAt: new Date(Date.now() + 30_000).toISOString(), + threadId, + runId: threadId === WORK_THREAD ? "work-run" : null, + realtime: { + clientUrl: `ws://127.0.0.1:${port}/client`, + topic: `thread:${threadId}`, + }, + }, + }; + } + const bot = path.match(/\/bots\/([^/]+)$/); + if (bot) + return { json: { bot: BOTS.find((one) => one.id === bot[1]) ?? BOT } }; + if (path === `${ORGANIZATION}/bots`) + return { json: { bots: BOTS, nextCursor: null } }; + if (/\/bots\/[^/]+\/grants$/.test(path)) return { json: botGrantsBody() }; + if (/\/bots\/[^/]+\/components$/.test(path)) + return { json: { components: [], nextCursor: null } }; + if (/\/computers\/[^/]+\/control$/.test(path)) + return { + json: { + holder: "bot", + since: "2026-11-30T15:00:00.000Z", + requested: false, + }, + }; + if (path === `${ORGANIZATION}/people/me/capabilities`) + return { json: { capabilities: {}, enforced: false } }; + if (path === `${ORGANIZATION}/people/me`) + return { + json: { + person: personBody({ + id: "dana", + name: "Dana Reyes", + email: "dana.reyes@northwind.example", + role: "admin", + }), + openbotVersion: "v1.2.3", + }, + }; + if (path === `${ORGANIZATION}/deployment`) + return { + json: { + generativeUi: true, + selfHostBanner: false, + // Not a computer of one's own: Sign out is offered. + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }, + }; + if (path === "/api/auth/sign-out" && method === "POST") + return { json: { success: true } }; + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return { status: 204 }; + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return { json: { sessions: [], nextCursor: null } }; + const thread = path.match(/\/threads\/([^/]+)\/messages$/); + if (thread) { + const threadId = decodeURIComponent(thread[1] ?? ""); + return { json: { messages: storedMessages(threadId) } }; + } + return undefined; +} + +/** + * What the gateway sends a browser that has joined a thread. The plan and notes threads are at + * rest: nothing to replay, and their history comes from the read. The work thread's Bot is running + * a command, started on another device: the turn so far, and the run going on. + */ +function gateway( + topic: string, + send: (name: string, payload: unknown) => void, +) { + if (topic !== `thread:${WORK_THREAD}`) { + send("replay_complete", { latestEventId: null }); + send("stream_idle", { latestEventId: null }); + return; + } + const event = (seq: number, fields: Record) => ({ + ...fields, + threadId: WORK_THREAD, + runId: "work-run", + run_id: "work-run", + metadata: { cpki_event_id: `work-${seq}`, cpki_event_seq: seq }, + }); + for (const one of [ + event(0, { type: "RUN_STARTED" }), + event(1, { + type: "TOOL_CALL_START", + toolCallId: "work-command", + toolCallName: "computer_run_command", + parentMessageId: "work-answer", + }), + event(2, { + type: "TOOL_CALL_ARGS", + toolCallId: "work-command", + delta: JSON.stringify({ command: WORK_COMMAND }), + }), + event(3, { type: "TOOL_CALL_END", toolCallId: "work-command" }), + ]) + send("ag_ui_event", one); + send("replay_complete", { latestEventId: "work-3" }); +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "conversation-kept.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name ?? id); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice((name ?? id).length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let script: string; +/** The app's stylesheet for every class the fixture can draw, built once. */ +let styles: string | undefined; + +function html(theme: string): string { + return `
    `; +} + +async function reply(request: Request, url: URL): Promise { + const path = url.pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + if (path.startsWith("/files/")) { + const font = join( + packageDir("@fontsource-variable/figtree"), + "files", + path.split("/").pop() ?? "", + ); + if (existsSync(font)) return new Response(Bun.file(font)); + } + if (path.startsWith("/api/")) { + const thread = path.match(/\/threads\/([^/]+)\/messages$/); + if (thread) { + const threadId = decodeURIComponent(thread[1] ?? ""); + reads.set(threadId, (reads.get(threadId) ?? 0) + 1); + // Held back, as a hosted read of a long thread is. + await sleep(READ_MS); + } + const said = answer(path, request.method); + if (!said) return Response.json({ detail: "Not found." }, { status: 404 }); + return said.json === undefined + ? new Response(null, { status: said.status ?? 200 }) + : Response.json(said.json, { status: said.status ?? 200 }); + } + return new Response(html(url.searchParams.get("theme") ?? "light"), { + headers: { "content-type": "text/html" }, + }); +} + +beforeAll(async () => { + if (!asked) return; + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request, bun) { + const url = new URL(request.url); + if (request.headers.get("upgrade") === "websocket") + return bun.upgrade(request, { data: {} }) + ? undefined + : new Response("upgrade failed", { status: 400 }); + return reply(request, url); + }, + websocket: { + message(socket, message) { + const [joinRef, ref, topic, name] = JSON.parse(String(message)) as [ + string | null, + string | null, + string, + string, + ]; + socket.send( + JSON.stringify([ + joinRef, + ref, + topic, + "phx_reply", + { status: "ok", response: {} }, + ]), + ); + if (name !== "phx_join") return; + gateway(topic, (event, payload) => { + if (socket.readyState === 1) + socket.send(JSON.stringify([joinRef, null, topic, event, payload])); + }); + }, + }, + }); + port = server.port ?? 0; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + server?.stop(true); +}); + +async function open( + engine: string, + theme: "light" | "dark", + conversation: string, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: { width: 1280, height: 800 }, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + await page.goto(`${origin()}/channel/${conversation}?theme=${theme}`); + return page; +} + +/** Styled for everything now on the page, once per page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + styles = await stylesheet([...new Set(classes)]); + await page.addStyleTag({ content: styles }); +} + +async function shoot(page: Page, step: string, name: string) { + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await style(page); + // Past the colours' transition from the browser's own, which a stylesheet added late starts. + await sleep(400); + await page.screenshot({ + path: join(shots, `conversation-kept-${step}-${name}.png`), + }); +} + +/** The conversation's words as drawn. */ +async function words(page: Page): Promise { + const main = page.locator("main").last(); + if ((await main.count()) === 0) return ""; + return (await main.innerText()).replace(/\s+/g, " "); +} + +/** Switch to a conversation with the sidebar, as a person does. */ +async function switchTo(page: Page, summary: string) { + await page + .getByRole("link", { name: new RegExp(summary) }) + .first() + .click(); +} + +/** The conversation's words, every frame for `ms` after `start`, each with when it was read. */ +async function framesFor(page: Page, ms: number) { + const seen: { at: number; text: string }[] = []; + const start = Date.now(); + while (Date.now() - start < ms) { + seen.push({ at: Date.now() - start, text: await words(page) }); + await sleep(16); + } + return seen; +} + +describe.skipIf(!asked)("going back to a conversation", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + test(`draws it at once, then what the server holds now, and keeps nothing past a sign-out, in ${engine}, ${theme}`, async () => { + added.plan = false; + added.notes = false; + reads.clear(); + const name = `${engine}-${theme}`; + const page = await open(engine, theme, "plan-conversation"); + try { + // Opened for the first time in this page: it loads as before. + await page.getByText(PLAN_ANSWER).waitFor({ timeout: 15_000 }); + await shoot(page, "plan-first-open", name); + + // To the conversation with the connected Bot, opened for the first time. + await switchTo(page, "Meeting notes"); + await page.getByText(NOTES_ANSWER).waitFor({ timeout: 15_000 }); + await shoot(page, "notes-first-open", name); + + // While the person is away, a message is added to the plan on another device. + added.plan = true; + const planReads = reads.get(PLAN_THREAD) ?? 0; + + // Back: on screen at once, before its history read has answered. + await switchTo(page, "Launch plan"); + await page.getByText(PLAN_ANSWER).waitFor({ timeout: AT_ONCE_MS }); + await shoot(page, "plan-back-kept", name); + expect(await words(page)).not.toContain(PLAN_ADDED); + expect(reads.get(PLAN_THREAD)).toBe(planReads + 1); + + // Then the read answers, and what was added on the other device comes in. + await page + .getByText(PLAN_ADDED) + .waitFor({ timeout: READ_MS + 5_000 }); + await shoot(page, "plan-back-fresh", name); + const fresh = await words(page); + expect(fresh.split(PLAN_ANSWER).length - 1).toBe(1); + expect(fresh.split(PLAN_QUESTION).length - 1).toBe(1); + + // The connected Bot's conversation the same way. + added.notes = true; + await switchTo(page, "Meeting notes"); + await page.getByText(NOTES_ANSWER).waitFor({ timeout: AT_ONCE_MS }); + await shoot(page, "notes-back-kept", name); + expect(await words(page)).not.toContain(NOTES_ADDED); + await page + .getByText(NOTES_ADDED) + .waitFor({ timeout: READ_MS + 5_000 }); + await shoot(page, "notes-back-fresh", name); + + // Signed out with the notes open, from the account menu. + await page + .getByRole("button", { name: /Dana Reyes/ }) + .first() + .click(); + // A click as the menu hears one: the page is styled only for its pictures. + await page + .getByRole("menuitem", { name: "Sign out" }) + .dispatchEvent("click"); + await page.waitForURL(/\/sign/, { timeout: 10_000 }); + + // And back, in the same page: nothing of either conversation was kept. + await switchTo(page, "Meeting notes"); + const afterSignOut = await framesFor(page, 1_200); + await shoot(page, "notes-after-sign-out-loading", name); + expect( + afterSignOut.filter((frame) => frame.text.includes(NOTES_ANSWER)), + ).toEqual([]); + await page + .getByText(NOTES_ADDED) + .waitFor({ timeout: READ_MS + 5_000 }); + await shoot(page, "notes-after-sign-out-loaded", name); + + await switchTo(page, "Launch plan"); + const planAfterSignOut = await framesFor(page, 1_200); + expect( + planAfterSignOut.filter((frame) => + frame.text.includes(PLAN_ANSWER), + ), + ).toEqual([]); + await page + .getByText(PLAN_ADDED) + .waitFor({ timeout: READ_MS + 5_000 }); + } finally { + await page.close(); + } + }, 120_000); + + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + test(`a Bot still running a command on another device reads as running, never interrupted, in ${engine}, ${theme}`, async () => { + reads.clear(); + const name = `${engine}-${theme}`; + const page = await open(engine, theme, "work-conversation"); + try { + await page + .getByText("Running a command") + .first() + .waitFor({ timeout: 15_000 }); + await shoot(page, "work-first-open", name); + + await switchTo(page, "Launch plan"); + await page.getByText(PLAN_ANSWER).waitFor({ timeout: 15_000 }); + + // Back while the command still runs: every frame says so, from the first. + await switchTo(page, "Test run"); + const frames = await framesFor(page, READ_MS + 1_000); + await shoot(page, "work-back", name); + const misread = frames.filter( + (frame) => + frame.text.includes("interrupted") || + frame.text.includes("Not completed"), + ); + expect(misread).toEqual([]); + expect(await words(page)).toContain("Running a command"); + } finally { + await page.close(); + } + }, 120_000); +}); diff --git a/app/tests/conversation-kept.fixture.tsx b/app/tests/conversation-kept.fixture.tsx new file mode 100644 index 0000000000..433b919d15 --- /dev/null +++ b/app/tests/conversation-kept.fixture.tsx @@ -0,0 +1,167 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { type InfiniteData, QueryClientProvider } from "@tanstack/react-query"; +import { + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { AppSidebar } from "@/components/app-sidebar/app-sidebar"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { SidebarShell } from "@/components/layout/sidebar-shell"; +import { SidebarInset } from "@/components/ui/sidebar"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { + type AgentChannel, + type ChannelPage, + channelKeys, +} from "@/lib/channels/queries"; +import { ActiveBotProvider } from "@/lib/copilot/active-bot"; +import { BotOffers } from "@/lib/copilot/bot-offer"; +import { ComputerTools } from "@/lib/copilot/computer-tools"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; + +/** + * Three conversations in the app's frame, for conversation-kept-browser.test.tsx to bundle and load + * in a browser: the real sidebar (its conversations, and the account menu with Sign out), and each + * conversation as its route draws it, keyed on its id so leaving one unmounts it, with the + * computer's tools registered as the app's provider registers them. One conversation is with a + * built-in Bot, one with a Bot connected over AG-UI, and one whose Bot is running a command on + * another device. What the server and the gateway answer comes from the test. + */ +setCurrentOrganization("default"); + +const PLAN: AgentChannel = { + id: "plan-conversation", + name: "Plan Bot", + agentIds: ["plan-bot"], + threadId: "plan-thread", + active: true, + lastMessageAt: "2026-11-30T18:00:00.000Z", +}; + +const NOTES: AgentChannel = { + id: "notes-conversation", + name: "Notes Bot", + agentIds: ["notes-bot"], + threadId: "notes-thread", + active: true, + lastMessageAt: "2026-11-30T17:00:00.000Z", +}; + +const WORK: AgentChannel = { + id: "work-conversation", + name: "Work Bot", + agentIds: ["work-bot"], + threadId: "work-thread", + active: true, + lastMessageAt: "2026-11-30T16:00:00.000Z", +}; + +const CONVERSATIONS = [PLAN, NOTES, WORK]; + +queryClient.setQueryDefaults(channelKeys.list(), { staleTime: Infinity }); +queryClient.setQueryData>(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...PLAN, + summary: "Launch plan", + lastMessage: "The plan has three steps.", + lastMessageAgentId: "plan-bot", + createdAt: "2026-11-30T17:59:00.000Z", + pinned: false, + lastReadAt: "2026-11-30T18:00:00.000Z", + }, + { + ...NOTES, + summary: "Meeting notes", + lastMessage: "Here are the notes from today.", + lastMessageAgentId: "notes-bot", + createdAt: "2026-11-30T16:59:00.000Z", + pinned: false, + lastReadAt: "2026-11-30T17:00:00.000Z", + }, + { + ...WORK, + summary: "Test run", + lastMessage: "Running the tests.", + lastMessageAgentId: "work-bot", + createdAt: "2026-11-30T15:59:00.000Z", + pinned: false, + lastReadAt: "2026-11-30T16:00:00.000Z", + // The server's roster: this conversation's Bot is working, on another device's turn. + busy: true, + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], +}); + +const rootRoute = createRootRoute({ + component: () => ( + + + + + + + + + + + ), +}); + +/** One conversation, as `routes/_authed/_app/channel/$channelId.tsx` draws its body. */ +function Conversation({ channelId }: { channelId: string }) { + const channel = CONVERSATIONS.find((one) => one.id === channelId); + if (!channel) return null; + return ( + + ); +} + +const conversationRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "channel/$channelId", + component: function ConversationRoute() { + const { channelId } = conversationRoute.useParams(); + return ; + }, +}); + +const router = createRouter({ + history: createBrowserHistory(), + routeTree: rootRoute.addChildren([ + conversationRoute, + createRoute({ + getParentRoute: () => rootRoute, + path: "$", + component: () => null, + }), + ]), +}); + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + + + + , + ); diff --git a/app/tests/kept-transcripts.test.ts b/app/tests/kept-transcripts.test.ts new file mode 100644 index 0000000000..38fca44d46 --- /dev/null +++ b/app/tests/kept-transcripts.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { + forgetTranscripts, + KEPT_TRANSCRIPT_MAX_CHARACTERS, + KEPT_TRANSCRIPTS, + KEPT_TRANSCRIPTS_MAX_CHARACTERS, + keepTranscript, + keptTranscript, + transcriptEra, +} from "@/lib/copilot/kept-transcripts"; +import { setCurrentOrganization } from "@/lib/organizations/current"; + +/** + * The conversations kept in memory so going back to one shows it at once, while its history is read + * again behind it. Without this, every click between conversations drew an empty transcript, then + * the whole history sliding in again. + */ + +function turn(id: string, content = `message ${id}`): Message { + return { id, role: "user", content }; +} + +afterEach(() => { + forgetTranscripts(); + setCurrentOrganization(undefined); +}); + +describe("keptTranscript", () => { + test("gives back what was kept for the thread", () => { + keepTranscript("thread-a", [turn("1"), turn("2")]); + + expect(keptTranscript("thread-a")?.map((message) => message.id)).toEqual([ + "1", + "2", + ]); + }); + + test("has nothing for a thread never kept", () => { + expect(keptTranscript("thread-unknown")).toBeNull(); + }); + + test("keeps its own copy, so a later change to the agent's list does not reach it", () => { + const live = [turn("1")]; + keepTranscript("thread-a", live); + live.push(turn("2")); + + expect(keptTranscript("thread-a")?.length).toBe(1); + }); + + test("an empty transcript is not kept, and forgets the one kept before", () => { + keepTranscript("thread-a", [turn("1")]); + keepTranscript("thread-a", []); + + expect(keptTranscript("thread-a")).toBeNull(); + }); + + test(`keeps the ${KEPT_TRANSCRIPTS} conversations opened most recently`, () => { + for (let index = 0; index <= KEPT_TRANSCRIPTS; index += 1) + keepTranscript(`thread-${index}`, [turn(`${index}`)]); + + // The first one kept is the one let go. + expect(keptTranscript("thread-0")).toBeNull(); + expect(keptTranscript(`thread-${KEPT_TRANSCRIPTS}`)).not.toBeNull(); + }); + + test("a conversation shown again counts as recent", () => { + for (let index = 0; index < KEPT_TRANSCRIPTS; index += 1) + keepTranscript(`thread-${index}`, [turn(`${index}`)]); + // Opened again, so the oldest is now thread-1. + keptTranscript("thread-0"); + keepTranscript("thread-new", [turn("new")]); + + expect(keptTranscript("thread-0")).not.toBeNull(); + expect(keptTranscript("thread-1")).toBeNull(); + }); + + test("a conversation too large to keep is not kept, and forgets the one kept before", () => { + keepTranscript("thread-a", [turn("1")]); + keepTranscript("thread-a", [ + turn("1", "x".repeat(KEPT_TRANSCRIPT_MAX_CHARACTERS)), + ]); + + expect(keptTranscript("thread-a")).toBeNull(); + }); + + test("all the conversations kept together stay under one budget, the one opened longest ago let go first", () => { + // Each just under the size one conversation may be, so only the budget across all of them binds. + const large = "x".repeat(KEPT_TRANSCRIPT_MAX_CHARACTERS - 100); + const fit = Math.floor( + KEPT_TRANSCRIPTS_MAX_CHARACTERS / KEPT_TRANSCRIPT_MAX_CHARACTERS, + ); + for (let index = 0; index <= fit; index += 1) + keepTranscript(`thread-${index}`, [turn(`${index}`, large)]); + + expect(keptTranscript("thread-0")).toBeNull(); + for (let index = 1; index <= fit; index += 1) + expect(keptTranscript(`thread-${index}`)).not.toBeNull(); + }); + + test("forgetTranscripts lets every conversation go", () => { + keepTranscript("thread-a", [turn("1")]); + forgetTranscripts(); + + expect(keptTranscript("thread-a")).toBeNull(); + }); + + test("a conversation opened before another organization is not kept as it closes after the change", () => { + setCurrentOrganization("org-1"); + const openedIn = transcriptEra(); + setCurrentOrganization("org-2"); + keepTranscript("thread-a", [turn("1")], openedIn); + + expect(keptTranscript("thread-a")).toBeNull(); + }); + + test("working in another organization lets every conversation go", () => { + setCurrentOrganization("org-1"); + keepTranscript("thread-a", [turn("1")]); + setCurrentOrganization("org-2"); + + expect(keptTranscript("thread-a")).toBeNull(); + }); +}); diff --git a/app/tests/preload.ts b/app/tests/preload.ts index a6b54f0d58..666069161d 100644 --- a/app/tests/preload.ts +++ b/app/tests/preload.ts @@ -33,11 +33,20 @@ import "./react-teardown"; import { beforeEach, mock } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { forgetTranscripts } from "../src/lib/copilot/kept-transcripts"; import { setCurrentOrganization } from "../src/lib/organizations/current"; setCurrentOrganization("default"); beforeEach(() => setCurrentOrganization("default")); +/* + * NOTHING KEPT OF A CONVERSATION FROM ONE TEST TO THE NEXT. What a conversation showed is kept in + * memory for the page (src/lib/copilot/kept-transcripts.ts), and every test file here is one page: + * a conversation one test opened would be drawn, from memory, in the next test that opens it, before + * that test's own history answered. Each test starts as a page just loaded, with nothing kept. + */ +beforeEach(() => forgetTranscripts()); + /* * msw's `HttpResponse` extends its `FetchResponse`, and `setupServer().listen()` re-parents that * class onto whatever `Response` is global at the time; `close()` puts back the one it found then. diff --git a/app/tests/transcript-messages.test.ts b/app/tests/transcript-messages.test.ts index 9b88c6656d..a272d8b4d1 100644 --- a/app/tests/transcript-messages.test.ts +++ b/app/tests/transcript-messages.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import type { Message } from "@ag-ui/core"; import { seedMessage, + shownTranscript, stashFirstMessage, takeFirstMessage, transcriptMessages, @@ -81,3 +82,36 @@ describe("the first-message stash", () => { expect(takeFirstMessage("channel_c")?.text).toBe("for c"); }); }); + +/** + * A conversation opened again: what was on screen last time shows while its history is read, so + * switching between conversations does not empty the transcript and slide every message in again. + */ +describe("shownTranscript", () => { + const kept: Message[] = [ + { id: "1", role: "user", content: "hi" }, + { id: "2", role: "assistant", content: "hello" }, + ]; + const live: Message[] = [{ id: "3", role: "user", content: "next" }]; + + test("while history loads, the kept conversation shows", () => { + expect(shownTranscript({ live, kept, loading: true })).toEqual({ + messages: kept, + fromKept: true, + }); + }); + + test("once history is in, the agent's messages show, even with one kept", () => { + expect(shownTranscript({ live, kept, loading: false })).toEqual({ + messages: live, + fromKept: false, + }); + }); + + test("a conversation with nothing kept loads as before", () => { + expect(shownTranscript({ live, kept: null, loading: true })).toEqual({ + messages: live, + fromKept: false, + }); + }); +}); From 1868fb3dd0338b1d10c0b110cb790eb54fa55bee Mon Sep 17 00:00:00 2001 From: Roman Yasel Date: Tue, 1 Dec 2026 03:28:14 +0300 Subject: [PATCH 017/224] Icons: Hugeicons set in place of Tabler, in the web app, the extension and OpenBot Desktop (#2206) Every icon in the web app, the extension and OpenBot Desktop now comes from Hugeicons' free set, through the icons module (app/src/components/icons) and Desktop's own icons file, in place of Tabler. --- .claude/skills/openbot-screen-layout/SKILL.md | 4 +- CHANGELOG.md | 3 + app/PRODUCT.md | 2 +- app/package.json | 3 +- app/src/components/admin/admin-sections.ts | 2 +- app/src/components/admin/admin-sidebar.tsx | 2 +- .../admin/controls/capabilities-section.tsx | 2 +- .../admin/controls/computer-sections.tsx | 2 +- .../admin/controls/describe-capabilities.tsx | 2 +- .../admin/controls/mcp-allowlist-section.tsx | 2 +- .../admin/controls/model-sections.tsx | 2 +- .../admin/controls/network-describe.tsx | 2 +- .../admin/controls/open-apps-section.tsx | 2 +- .../admin/controls/people-learning.tsx | 2 +- .../admin/controls/purge-saved-logins.tsx | 2 +- .../admin/controls/recording-section.tsx | 2 +- .../admin/controls/sign-in-section.tsx | 2 +- .../admin/controls/skill-sharing-section.tsx | 2 +- app/src/components/agents/agent-card.tsx | 2 +- .../components/agents/custom-agent-cta.tsx | 2 +- app/src/components/agents/handoff-panel.tsx | 2 +- app/src/components/agents/new-bot-sheet.tsx | 2 +- app/src/components/app-sidebar/bots-panel.tsx | 2 +- .../app-sidebar/channel-item-content.tsx | 2 +- app/src/components/app-sidebar/channel.tsx | 2 +- .../app-sidebar/conversations-panel.tsx | 2 +- .../app-sidebar/desktop-app-item.tsx | 2 +- .../components/app-sidebar/section-strip.tsx | 2 +- .../app-sidebar/troubleshooting-logs-item.tsx | 2 +- app/src/components/approvals/bot-rules.tsx | 2 +- .../approvals/conversation-allowances.tsx | 2 +- .../components/approvals/describe-rules.tsx | 2 +- .../components/approvals/question-notice.tsx | 2 +- app/src/components/approvals/rules.tsx | 2 +- app/src/components/approvals/settings.tsx | 2 +- .../approvals/shared-use-requests.tsx | 2 +- .../components/approvals/team-settings.tsx | 2 +- app/src/components/approvals/waiting.tsx | 2 +- app/src/components/audit/ask-the-trail.tsx | 2 +- app/src/components/audit/audit-filters.tsx | 2 +- app/src/components/audit/audit-table.tsx | 2 +- app/src/components/auth/cloud-sign-in.tsx | 2 +- .../components/auth/company-sign-in-page.tsx | 2 +- app/src/components/bot-profile/access.tsx | 2 +- app/src/components/bot-profile/activity.tsx | 2 +- .../components/bot-profile/default-model.tsx | 2 +- app/src/components/bot-profile/manage.tsx | 2 +- .../components/bot-profile/pause-banner.tsx | 2 +- app/src/components/bot-profile/profile.tsx | 2 +- .../components/bot-profile/settings-rows.tsx | 2 +- app/src/components/bot-profile/setup.tsx | 2 +- app/src/components/bot-profile/sharing.tsx | 2 +- app/src/components/bots/bot-roster.tsx | 2 +- .../components/boundaries/dry-run-changes.tsx | 2 +- .../components/boundaries/rule-reading.tsx | 2 +- app/src/components/browser/browser-bar.tsx | 2 +- app/src/components/browser/browser-screen.tsx | 2 +- app/src/components/browser/learning-next.tsx | 2 +- .../components/browser/narration-choice.tsx | 2 +- app/src/components/browser/narration.tsx | 2 +- app/src/components/browser/recording.tsx | 2 +- app/src/components/browser/teach-steps.tsx | 2 +- .../components/browser/your-recordings.tsx | 2 +- .../components/channels/attachment-view.tsx | 2 +- .../components/channels/chat-transcript.tsx | 2 +- .../components/channels/coding-tool-cards.tsx | 2 +- .../channels/composer/attachment-strip.tsx | 2 +- .../components/channels/composer/composer.tsx | 2 +- .../channels/composer/dictation-controls.tsx | 2 +- .../channels/composer/model-picker.tsx | 2 +- .../channels/composer/rejected-files.tsx | 2 +- .../channels/conversation-actions.tsx | 2 +- app/src/components/channels/file-icon.tsx | 6 +- .../channels/generated-image-card.tsx | 6 +- app/src/components/channels/group-people.tsx | 2 +- .../components/channels/research-results.tsx | 2 +- .../components/channels/sent-file-card.tsx | 2 +- app/src/components/channels/tool-activity.tsx | 2 +- .../components/channels/voice-call-widget.tsx | 2 +- .../components/channels/voice-chat-card.tsx | 2 +- app/src/components/computer/activity-log.tsx | 2 +- app/src/components/computer/bot-browser.tsx | 2 +- .../components/computer/computer-blocked.tsx | 2 +- .../components/computer/computer-controls.tsx | 2 +- .../components/computer/computer-panel.tsx | 6 +- .../components/computer/computer-starting.tsx | 6 +- app/src/components/computer/computer-view.tsx | 2 +- .../computer/desktop-illustration.tsx | 4 +- .../components/computer/help-request-card.tsx | 2 +- .../components/computer/terminal-block.tsx | 2 +- .../connections/identity-connection-page.tsx | 2 +- .../components/decisions/decision-card.tsx | 2 +- app/src/components/delivery/reaching-you.tsx | 2 +- app/src/components/edition/business-link.tsx | 2 +- app/src/components/edition/for-a-team.tsx | 2 +- app/src/components/edition/openbot-logo.tsx | 4 +- .../edition/team-features-dialog.tsx | 2 +- app/src/components/icons/index.tsx | 613 ++++++++++++++++++ app/src/components/icons/waveform.tsx | 25 +- .../components/layout/connection-banner.tsx | 2 +- app/src/components/layout/detail-panel.tsx | 2 +- app/src/components/layout/page-shell.tsx | 2 +- .../components/layout/self-host-banner.tsx | 2 +- app/src/components/layout/sidebar-toggle.tsx | 2 +- app/src/components/layout/strip.tsx | 4 +- app/src/components/layout/update-banner.tsx | 2 +- .../learning/learned-skill-dialog.tsx | 2 +- app/src/components/manage/audit-page.tsx | 2 +- app/src/components/manage/computers-page.tsx | 2 +- .../components/manage/credentials-page.tsx | 2 +- app/src/components/manage/describe-grants.tsx | 2 +- app/src/components/manage/plugin-bot-page.tsx | 2 +- app/src/components/manage/plugin-page.tsx | 2 +- .../components/manage/plugin-tool-page.tsx | 2 +- .../components/manage/plugins-list-page.tsx | 4 +- app/src/components/manage/skill-page.tsx | 2 +- app/src/components/manage/skills-page.tsx | 2 +- .../manage/workspace-snapshots-section.tsx | 2 +- app/src/components/memory/memories.tsx | 2 +- app/src/components/memory/sources.tsx | 2 +- .../components/moves/moved-apps-notice.tsx | 2 +- .../moves/moved-elsewhere-banner.tsx | 2 +- .../components/navigation/command-menu.tsx | 2 +- app/src/components/needs-you/board-row.tsx | 2 +- app/src/components/needs-you/board.tsx | 2 +- app/src/components/needs-you/needs-you.tsx | 2 +- .../components/needs-you/stalled-handoffs.tsx | 2 +- .../notifications/notifications-offer-row.tsx | 2 +- .../notifications/notify-prompt.tsx | 2 +- app/src/components/onboarding/ai-step.tsx | 2 +- .../onboarding/ask-first-switch.tsx | 2 +- .../onboarding/demos/welcome-demo.tsx | 2 +- .../onboarding/onboarding-frame.tsx | 2 +- .../onboarding/organization-flow.tsx | 2 +- .../organizations/invitations-page.tsx | 2 +- .../left-organization-banner.tsx | 2 +- .../organizations/organization-menu.tsx | 2 +- .../organization-settings-page.tsx | 2 +- .../organizations/person-avatar.tsx | 2 +- .../sent-invitations-section.tsx | 2 +- app/src/components/passwords/sign-in-form.tsx | 2 +- .../components/plugins/access-requests.tsx | 2 +- .../components/plugins/broker-directory.tsx | 2 +- .../plugins/brokered-account-row.tsx | 2 +- app/src/components/plugins/plugin-logo.tsx | 2 +- .../plugins/shared-approval-fields.tsx | 2 +- .../components/recorder/recorder-collects.tsx | 2 +- .../components/responsibilities/goal-page.tsx | 2 +- .../components/responsibilities/triggers.tsx | 2 +- app/src/components/routines/bot-group.tsx | 8 +- app/src/components/routines/delete-row.tsx | 2 +- .../components/routines/goal-schedules.tsx | 2 +- .../routines/new-routine-button.tsx | 2 +- .../routines/routine-detail-missing.tsx | 2 +- app/src/components/routines/routine-page.tsx | 2 +- .../routines/routines-connection-page.tsx | 2 +- app/src/components/routines/routines-list.tsx | 2 +- .../settings-tools/add-custom-mcp-card.tsx | 2 +- .../settings-tools/admin-card-parts.tsx | 2 +- .../settings-tools/get-my-bots-card.tsx | 2 +- .../settings-tools/get-my-settings-card.tsx | 2 +- .../get-organization-settings-card.tsx | 2 +- .../settings-tools/how-do-i-card.tsx | 2 +- .../settings-tools/manage-people-card.tsx | 2 +- .../settings-tools/manage-teams-card.tsx | 2 +- .../components/settings-tools/screen-link.tsx | 2 +- .../settings-tools/settings-change-card.tsx | 10 +- .../settings-tools/settings-read-card.tsx | 4 +- .../settings-tools/update-bot-apps-card.tsx | 2 +- .../settings-tools/update-my-bot-card.tsx | 2 +- .../update-my-settings-card.tsx | 6 +- .../update-organization-settings-card.tsx | 5 +- .../settings-tools/where-do-i-change-card.tsx | 2 +- .../settings/ai-connection-chooser.tsx | 2 +- .../settings/ai-connection-list.tsx | 2 +- app/src/components/settings/ai-connection.tsx | 2 +- app/src/components/settings/api-keys.tsx | 2 +- .../settings/browser-notifications.tsx | 2 +- .../settings/browsers/connected-browsers.tsx | 2 +- .../settings/browsers/this-browser.tsx | 2 +- .../settings/chatgpt-browser-sign-in.tsx | 2 +- app/src/components/settings/check-ins.tsx | 2 +- .../components/settings/company-sign-in.tsx | 2 +- .../settings/connection-sections.tsx | 2 +- .../components/settings/delete-account.tsx | 2 +- app/src/components/settings/devices.tsx | 2 +- .../components/settings/github-sources.tsx | 2 +- .../components/settings/learning-review.tsx | 2 +- .../components/settings/learning-sharing.tsx | 2 +- .../settings/linked-accounts.test.tsx | 2 +- .../components/settings/linked-accounts.tsx | 2 +- .../settings/message-list-preference.tsx | 2 +- app/src/components/settings/profile.tsx | 2 +- .../components/settings/provider-pages.tsx | 2 +- .../components/settings/settings-sidebar.tsx | 2 +- .../settings/standing-instructions.tsx | 2 +- .../components/settings/star-on-github.tsx | 2 +- app/src/components/settings/theme-row.tsx | 2 +- .../settings/this-computer-sections.tsx | 2 +- .../components/settings/update-routing.tsx | 2 +- app/src/components/settings/usage-data.tsx | 2 +- app/src/components/settings/your-ai.tsx | 2 +- app/src/components/setup/setup-checklist.tsx | 2 +- app/src/components/skills/skill-tools.tsx | 2 +- .../skills/skills-settings-page.tsx | 2 +- .../components/star-prompt/star-prompt.tsx | 2 +- .../components/suggestions/check-in-page.tsx | 2 +- .../suggestions/proactive-panel.tsx | 2 +- .../components/suggestions/suggestion-row.tsx | 2 +- app/src/components/tasks/task-details.tsx | 2 +- app/src/components/tasks/task-row.tsx | 2 +- app/src/components/tasks/task-steer.tsx | 2 +- app/src/components/tasks/task-thread.tsx | 2 +- .../team-grants/team-grants-row.tsx | 2 +- app/src/components/teams/new-team-page.tsx | 2 +- app/src/components/teams/people-typeahead.tsx | 2 +- app/src/components/teams/team-models.tsx | 2 +- app/src/components/teams/team-page.tsx | 2 +- app/src/components/teams/teams-page.tsx | 2 +- app/src/components/ui/carousel.tsx | 2 +- app/src/components/ui/checkbox.tsx | 2 +- app/src/components/ui/combobox.tsx | 2 +- app/src/components/ui/context-menu.tsx | 2 +- app/src/components/ui/dialog.tsx | 2 +- app/src/components/ui/dropdown-menu.tsx | 2 +- app/src/components/ui/message-scroller.tsx | 2 +- app/src/components/ui/questionnaire.tsx | 2 +- app/src/components/ui/select.tsx | 2 +- app/src/components/ui/sheet.tsx | 2 +- app/src/components/ui/sidebar.tsx | 2 +- app/src/components/ui/toast.tsx | 2 +- app/src/components/vault/saved-logins.tsx | 2 +- app/src/components/vault/vault-page.tsx | 2 +- app/src/components/what-if/action-chips.tsx | 2 +- app/src/components/what-if/what-if-result.tsx | 2 +- app/src/components/what-if/why-button.tsx | 2 +- .../connect-windows-computer.tsx | 2 +- .../windows-computer-choice.tsx | 2 +- .../windows-computer-page.tsx | 8 +- app/src/lib/copilot/check-in-offer-tool.tsx | 2 +- app/src/lib/copilot/sign-in-tool.tsx | 2 +- app/src/lib/markdown.tsx | 2 +- app/src/lib/navigation.ts | 2 +- app/src/lib/primitives.ts | 2 +- app/src/routes/_authed/_app/bot.tsx | 2 +- app/src/routes/_authed/_app/bots.index.tsx | 2 +- .../_authed/_app/channel/$channelId.tsx | 2 +- .../routes/_authed/_app/connections.$key.tsx | 10 +- .../routes/_authed/_app/connections.index.tsx | 2 +- app/src/routes/_authed/_app/reconnect.tsx | 2 +- .../_authed/admin/approvals_.guidance.tsx | 2 +- app/src/routes/_authed/admin/boundaries.tsx | 2 +- .../routes/_authed/admin/boundaries_.new.tsx | 2 +- .../routes/_authed/admin/components/$name.tsx | 2 +- .../_authed/admin/identity-providers.tsx | 2 +- app/src/routes/_authed/admin/index.tsx | 2 +- app/src/routes/_authed/admin/learning.tsx | 2 +- app/src/routes/_authed/admin/management.tsx | 2 +- app/src/routes/_authed/admin/people.tsx | 2 +- app/src/routes/_authed/admin/proactive.tsx | 2 +- app/src/routes/_authed/admin/what-if.tsx | 2 +- .../settings/components-gallery/$name.tsx | 2 +- app/src/skins/opendots/computer-pane.tsx | 2 +- app/src/skins/opendots/frame.tsx | 2 +- app/src/skins/opendots/persona.tsx | 2 +- app/src/skins/opendots/sidebar.tsx | 2 +- app/src/skins/openduet/header.tsx | 2 +- app/src/skins/openduet/icons.ts | 62 +- app/src/skins/openduet/menu-sheet.tsx | 2 +- app/src/skins/openduet/tab-bar.tsx | 2 +- app/src/skins/openfuse/bots-sheet.tsx | 2 +- app/src/skins/openfuse/frame.tsx | 2 +- app/src/skins/openfuse/menu-sheet.tsx | 2 +- .../skins/openfuse/notifications-sheet.tsx | 2 +- app/src/skins/openfuse/screens/activity.tsx | 2 +- app/src/skins/openfuse/screens/ideas.tsx | 2 +- app/src/skins/openfuse/ui.tsx | 2 +- app/src/skins/skin-picker.tsx | 2 +- app/src/theme.css | 9 - app/tests/admin-skills-pages.test.tsx | 2 +- app/tests/bot-activity-groups.test.tsx | 10 +- app/tests/bot-manage.test.tsx | 4 +- app/tests/bot-profile-notice.test.tsx | 2 +- app/tests/icon-set.test.ts | 118 ++++ app/tests/model-picker.test.tsx | 6 +- app/tests/needs-you.test.tsx | 2 +- app/tests/office-file-cards.test.tsx | 6 +- app/tests/organization-menu-names.fixture.tsx | 2 +- app/tests/personal-connections.test.tsx | 2 +- app/tests/roster-working.fixture.tsx | 2 +- app/tests/routine-box-line.test.tsx | 2 +- app/tests/routines-bot-group.test.tsx | 2 +- app/tests/routines-merged.test.tsx | 2 +- app/tests/screen-link-style.ts | 2 +- app/tests/settings-tool-cards-core.test.tsx | 2 +- app/tests/sidebar-window-buttons.fixture.tsx | 2 +- app/tests/sidebar-zoom-drag.fixture.tsx | 2 +- app/tests/stopped-connection-notice.test.tsx | 6 +- app/tests/strip.test.tsx | 2 +- app/tests/team-models-screens-layout.test.tsx | 4 +- app/tests/transcript-attachments.test.tsx | 6 +- app/tests/ui-look-theme.test.ts | 44 +- app/tests/vault.test.tsx | 2 +- app/tests/web-push.fixture.tsx | 2 +- biome.json | 2 +- bun.lock | 14 +- desktop/bun.lock | 11 +- desktop/package.json | 3 +- desktop/src/BusinessBooker.tsx | 2 +- desktop/src/CopilotKitAccount.tsx | 2 +- desktop/src/EndpointMark.tsx | 8 +- desktop/src/MoveToCloud.tsx | 12 +- desktop/src/SelfContained.tsx | 4 +- desktop/src/Welcome.tsx | 2 +- desktop/src/icons.tsx | 116 ++++ desktop/workbench/CommandsPanel.tsx | 2 +- desktop/workbench/RequestLog.tsx | 2 +- desktop/workbench/Shell.tsx | 2 +- docs/app-guidelines.md | 5 +- docs/design-system.md | 9 +- extension/package.json | 3 +- extension/src/pages/connect/connect-page.tsx | 2 +- extension/src/pages/options/options.tsx | 2 +- extension/src/pages/popup/notices.tsx | 2 +- extension/src/pages/popup/popup.tsx | 2 +- extension/src/pages/popup/record-form.tsx | 2 +- extension/src/pages/popup/recording-view.tsx | 2 +- extension/src/pages/setup/setup-page.tsx | 2 +- extension/src/pages/ui/capture-rows.tsx | 2 +- extension/src/pages/ui/security-floor.tsx | 2 +- shared/openbot-for-business.ts | 2 +- 331 files changed, 1309 insertions(+), 470 deletions(-) create mode 100644 app/src/components/icons/index.tsx create mode 100644 app/tests/icon-set.test.ts create mode 100644 desktop/src/icons.tsx diff --git a/.claude/skills/openbot-screen-layout/SKILL.md b/.claude/skills/openbot-screen-layout/SKILL.md index 6550e63272..2ca169bed6 100644 --- a/.claude/skills/openbot-screen-layout/SKILL.md +++ b/.claude/skills/openbot-screen-layout/SKILL.md @@ -122,8 +122,8 @@ button. ### Procedure 2: Compose a row -1. `ItemMedia variant="icon"` holds a leading icon from `@tabler/icons-react`, drawn as a 16px glyph - on a 32px muted tile. It is what makes a card of rows scannable; a row without one reads as a +1. `ItemMedia variant="icon"` holds a leading icon from `@/components/icons`, drawn as a 16px glyph on + a 32px muted tile. It is what makes a card of rows scannable; a row without one reads as a paragraph. Pass the bare icon — the variant sizes and colours it — and use plain `ItemMedia` only for something that is its own picture, such as a Bot's avatar. 2. `ItemContent` holds `ItemTitle` and, where the row needs a second line, `ItemDescription`. diff --git a/CHANGELOG.md b/CHANGELOG.md index dfcaed6d89..3e4421233c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2042,6 +2042,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. with rings of dots that brighten as you type, and the page rises in on the first Home of a visit. Nothing moves when your system asks for less motion. Skins keep their own look. OpenBot Desktop's setup window and the phone app take the same grays. +- **New icons, the same in every app.** The web app, the browser extension and OpenBot Desktop draw + their icons from Hugeicons' free set instead of Tabler: rounder, with a slightly lighter line, at + the same sizes and in the same places. Each icon keeps its meaning, and the skins take them too. - **Product telemetry says which kind of install sent it.** An event's `environment` was read from `NODE_ENV`, which a Compose install and OpenBot Desktop leave empty, so every event said `unknown`. It now comes from the build: a release, a release candidate or an internal build says diff --git a/app/PRODUCT.md b/app/PRODUCT.md index bcd68c31fb..4e666f40ac 100644 --- a/app/PRODUCT.md +++ b/app/PRODUCT.md @@ -34,7 +34,7 @@ Bots are coworkers, and you own them. Each Bot has a computer of its own (a real - The skin system stays. This redesign replaces the default `openbot` skin. The other skins stay as alternates. - Desktop and mobile must both work at native quality. - Dense admin screens (audit log, approvals, tables, settings) must stay easy to scan. -- Stack: React 19, Vite, Tailwind 4, shadcn and Base UI components, Tabler icons, Motion. +- Stack: React 19, Vite, Tailwind 4, shadcn and Base UI components, Hugeicons, Motion. ## Brand Commitments diff --git a/app/package.json b/app/package.json index 8607f3b67d..e943e393f5 100644 --- a/app/package.json +++ b/app/package.json @@ -21,11 +21,12 @@ "@better-auth/sso": "^1.7.1", "@copilotkit/react-core": "1.88.0", "@fontsource-variable/figtree": "^5.3.0", + "@hugeicons/core-free-icons": "^4.4.0", + "@hugeicons/react": "^1.1.10", "@openbot/shared": "workspace:*", "@shadcn/react": "^0.3.0", "@streamdown/code": "2.0.0", "@streamdown/math": "1.0.3", - "@tabler/icons-react": "^3.36.1", "@tanstack/react-form": "^1.33.5", "@tanstack/react-hotkeys": "^0.10.0", "@tanstack/react-query": "^5.101.4", diff --git a/app/src/components/admin/admin-sections.ts b/app/src/components/admin/admin-sections.ts index 485d3cffb5..6f21c58b84 100644 --- a/app/src/components/admin/admin-sections.ts +++ b/app/src/components/admin/admin-sections.ts @@ -10,7 +10,7 @@ import { IconUsers, IconUsersGroup, IconZoomQuestion, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import type { LinkOptions } from "@tanstack/react-router"; import type * as React from "react"; diff --git a/app/src/components/admin/admin-sidebar.tsx b/app/src/components/admin/admin-sidebar.tsx index 7216d062f7..3d1a8e9126 100644 --- a/app/src/components/admin/admin-sidebar.tsx +++ b/app/src/components/admin/admin-sidebar.tsx @@ -1,4 +1,4 @@ -import { IconArrowLeft } from "@tabler/icons-react"; +import { IconArrowLeft } from "@/components/icons"; import { Link, type LinkOptions } from "@tanstack/react-router"; import type * as React from "react"; import { useAdminSections } from "@/components/admin/admin-sections"; diff --git a/app/src/components/admin/controls/capabilities-section.tsx b/app/src/components/admin/controls/capabilities-section.tsx index e7e8743913..2cf85848a4 100644 --- a/app/src/components/admin/controls/capabilities-section.tsx +++ b/app/src/components/admin/controls/capabilities-section.tsx @@ -3,7 +3,7 @@ import { IconSparkles, IconToggleRight, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/components/admin/controls/computer-sections.tsx b/app/src/components/admin/controls/computer-sections.tsx index f1a79439c7..a4d8342c44 100644 --- a/app/src/components/admin/controls/computer-sections.tsx +++ b/app/src/components/admin/controls/computer-sections.tsx @@ -7,7 +7,7 @@ import { IconPlus, IconUsersGroup, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useId, useState } from "react"; import { useEdition } from "@/components/edition/for-a-team"; diff --git a/app/src/components/admin/controls/describe-capabilities.tsx b/app/src/components/admin/controls/describe-capabilities.tsx index 312d11ca6d..fc7b24eaaa 100644 --- a/app/src/components/admin/controls/describe-capabilities.tsx +++ b/app/src/components/admin/controls/describe-capabilities.tsx @@ -12,7 +12,7 @@ import { IconUser, IconUserShield, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import type { UseQueryResult } from "@tanstack/react-query"; import { Fragment } from "react"; import type { AuditEvent } from "@/components/audit/audit-cells"; diff --git a/app/src/components/admin/controls/mcp-allowlist-section.tsx b/app/src/components/admin/controls/mcp-allowlist-section.tsx index c0cc828c64..d620bcead6 100644 --- a/app/src/components/admin/controls/mcp-allowlist-section.tsx +++ b/app/src/components/admin/controls/mcp-allowlist-section.tsx @@ -3,7 +3,7 @@ import { IconKey, IconPlug, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useState } from "react"; import { PageRows } from "@/components/layout/page-shell"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/admin/controls/model-sections.tsx b/app/src/components/admin/controls/model-sections.tsx index 92b37d6cdd..a0e94bd078 100644 --- a/app/src/components/admin/controls/model-sections.tsx +++ b/app/src/components/admin/controls/model-sections.tsx @@ -10,7 +10,7 @@ import { IconShieldLock, IconSparkles, IconUsers, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQueries, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment, useState } from "react"; diff --git a/app/src/components/admin/controls/network-describe.tsx b/app/src/components/admin/controls/network-describe.tsx index 32f87a8ca1..666d0b4806 100644 --- a/app/src/components/admin/controls/network-describe.tsx +++ b/app/src/components/admin/controls/network-describe.tsx @@ -1,4 +1,4 @@ -import { IconWorld, IconWorldOff } from "@tabler/icons-react"; +import { IconWorld, IconWorldOff } from "@/components/icons"; import { keepPreviousData, useQuery } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { DescribeField } from "@/components/boundaries/describe-rule"; diff --git a/app/src/components/admin/controls/open-apps-section.tsx b/app/src/components/admin/controls/open-apps-section.tsx index 7e5092e56f..3858ff0ba5 100644 --- a/app/src/components/admin/controls/open-apps-section.tsx +++ b/app/src/components/admin/controls/open-apps-section.tsx @@ -1,4 +1,4 @@ -import { IconLock, IconLockOpen } from "@tabler/icons-react"; +import { IconLock, IconLockOpen } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useId, useState } from "react"; import { useEdition } from "@/components/edition/for-a-team"; diff --git a/app/src/components/admin/controls/people-learning.tsx b/app/src/components/admin/controls/people-learning.tsx index 7f73f750a3..9f83987534 100644 --- a/app/src/components/admin/controls/people-learning.tsx +++ b/app/src/components/admin/controls/people-learning.tsx @@ -5,7 +5,7 @@ import { IconShare, IconSparkles, IconUserCheck, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, type ReactNode, useState } from "react"; import { diff --git a/app/src/components/admin/controls/purge-saved-logins.tsx b/app/src/components/admin/controls/purge-saved-logins.tsx index c228cb841d..3e3289f122 100644 --- a/app/src/components/admin/controls/purge-saved-logins.tsx +++ b/app/src/components/admin/controls/purge-saved-logins.tsx @@ -1,4 +1,4 @@ -import { IconTrash } from "@tabler/icons-react"; +import { IconTrash } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/admin/controls/recording-section.tsx b/app/src/components/admin/controls/recording-section.tsx index d00588cff5..6918249bf4 100644 --- a/app/src/components/admin/controls/recording-section.tsx +++ b/app/src/components/admin/controls/recording-section.tsx @@ -1,4 +1,4 @@ -import { IconChartBar, IconTerminal2 } from "@tabler/icons-react"; +import { IconChartBar, IconTerminal2 } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { PageEmpty, PageRows } from "@/components/layout/page-shell"; import { diff --git a/app/src/components/admin/controls/sign-in-section.tsx b/app/src/components/admin/controls/sign-in-section.tsx index d5f93be1a9..9262dc777a 100644 --- a/app/src/components/admin/controls/sign-in-section.tsx +++ b/app/src/components/admin/controls/sign-in-section.tsx @@ -1,4 +1,4 @@ -import { IconFingerprint, IconShieldLock } from "@tabler/icons-react"; +import { IconFingerprint, IconShieldLock } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { PageRows } from "@/components/layout/page-shell"; import { diff --git a/app/src/components/admin/controls/skill-sharing-section.tsx b/app/src/components/admin/controls/skill-sharing-section.tsx index c96fedca2d..6980f19dcc 100644 --- a/app/src/components/admin/controls/skill-sharing-section.tsx +++ b/app/src/components/admin/controls/skill-sharing-section.tsx @@ -1,4 +1,4 @@ -import { IconShare } from "@tabler/icons-react"; +import { IconShare } from "@/components/icons"; import { PageRows } from "@/components/layout/page-shell"; import { Item, diff --git a/app/src/components/agents/agent-card.tsx b/app/src/components/agents/agent-card.tsx index 2ac1020e0f..4b200d9935 100644 --- a/app/src/components/agents/agent-card.tsx +++ b/app/src/components/agents/agent-card.tsx @@ -1,4 +1,4 @@ -import { IconArrowRight } from "@tabler/icons-react"; +import { IconArrowRight } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { AbstractAvatar } from "@/components/agents/abstract-avatar"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/agents/custom-agent-cta.tsx b/app/src/components/agents/custom-agent-cta.tsx index c74648f4a8..2ca57c8c3c 100644 --- a/app/src/components/agents/custom-agent-cta.tsx +++ b/app/src/components/agents/custom-agent-cta.tsx @@ -1,5 +1,5 @@ import { WEB_HARNESSES } from "@openbot/shared/harnesses"; -import { IconChevronRight } from "@tabler/icons-react"; +import { IconChevronRight } from "@/components/icons"; import { HarnessMark } from "@/components/agents/harness-mark"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/agents/handoff-panel.tsx b/app/src/components/agents/handoff-panel.tsx index 2e6c92b811..9033c940ba 100644 --- a/app/src/components/agents/handoff-panel.tsx +++ b/app/src/components/agents/handoff-panel.tsx @@ -1,4 +1,4 @@ -import { IconArrowsExchange, IconBolt, IconLock } from "@tabler/icons-react"; +import { IconArrowsExchange, IconBolt, IconLock } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment } from "react"; import { AbstractAvatar } from "@/components/agents/abstract-avatar"; diff --git a/app/src/components/agents/new-bot-sheet.tsx b/app/src/components/agents/new-bot-sheet.tsx index f43879688f..f80868c312 100644 --- a/app/src/components/agents/new-bot-sheet.tsx +++ b/app/src/components/agents/new-bot-sheet.tsx @@ -10,7 +10,7 @@ import { IconInfoCircle, IconLock, IconUsers, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type UseQueryResult, useMutation, diff --git a/app/src/components/app-sidebar/bots-panel.tsx b/app/src/components/app-sidebar/bots-panel.tsx index f9b9c0d4a5..30460283aa 100644 --- a/app/src/components/app-sidebar/bots-panel.tsx +++ b/app/src/components/app-sidebar/bots-panel.tsx @@ -3,7 +3,7 @@ import { IconMessagePlus, IconPlus, IconSearch, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useQuery, diff --git a/app/src/components/app-sidebar/channel-item-content.tsx b/app/src/components/app-sidebar/channel-item-content.tsx index a751a4149d..1eab5d590c 100644 --- a/app/src/components/app-sidebar/channel-item-content.tsx +++ b/app/src/components/app-sidebar/channel-item-content.tsx @@ -1,4 +1,4 @@ -import { IconPinFilled } from "@tabler/icons-react"; +import { IconPinFilled } from "@/components/icons"; import { ChannelAvatar } from "@/components/channels/avatar"; import type { ConversationView } from "@/lib/settings/conversation-view"; import type { MessageListEmphasis } from "@/lib/settings/message-list"; diff --git a/app/src/components/app-sidebar/channel.tsx b/app/src/components/app-sidebar/channel.tsx index baa0c1d284..c1109c5b15 100644 --- a/app/src/components/app-sidebar/channel.tsx +++ b/app/src/components/app-sidebar/channel.tsx @@ -3,7 +3,7 @@ import { IconPin, IconPinnedOff, IconTrash, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Link, useNavigate, useParams } from "@tanstack/react-router"; import { memo, useState } from "react"; diff --git a/app/src/components/app-sidebar/conversations-panel.tsx b/app/src/components/app-sidebar/conversations-panel.tsx index e8b6f6ffc9..760415dbb8 100644 --- a/app/src/components/app-sidebar/conversations-panel.tsx +++ b/app/src/components/app-sidebar/conversations-panel.tsx @@ -1,4 +1,4 @@ -import { IconMessagePlus, IconSearch } from "@tabler/icons-react"; +import { IconMessagePlus, IconSearch } from "@/components/icons"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link, useParams } from "@tanstack/react-router"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; diff --git a/app/src/components/app-sidebar/desktop-app-item.tsx b/app/src/components/app-sidebar/desktop-app-item.tsx index 2e0d7b3412..bc705260c0 100644 --- a/app/src/components/app-sidebar/desktop-app-item.tsx +++ b/app/src/components/app-sidebar/desktop-app-item.tsx @@ -1,4 +1,4 @@ -import { IconDeviceDesktopDown } from "@tabler/icons-react"; +import { IconDeviceDesktopDown } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; diff --git a/app/src/components/app-sidebar/section-strip.tsx b/app/src/components/app-sidebar/section-strip.tsx index f2e1ddcdff..4221ea7529 100644 --- a/app/src/components/app-sidebar/section-strip.tsx +++ b/app/src/components/app-sidebar/section-strip.tsx @@ -1,4 +1,4 @@ -import { type Icon, IconLogout, IconMessages } from "@tabler/icons-react"; +import { type Icon, IconLogout, IconMessages } from "@/components/icons"; import { Link, useRouterState } from "@tanstack/react-router"; import type { ReactNode } from "react"; import AgentOrb from "@/components/agents/orb/agent-orb"; diff --git a/app/src/components/app-sidebar/troubleshooting-logs-item.tsx b/app/src/components/app-sidebar/troubleshooting-logs-item.tsx index 8f4aa9662b..8f47af88a7 100644 --- a/app/src/components/app-sidebar/troubleshooting-logs-item.tsx +++ b/app/src/components/app-sidebar/troubleshooting-logs-item.tsx @@ -1,4 +1,4 @@ -import { IconLifebuoy } from "@tabler/icons-react"; +import { IconLifebuoy } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; diff --git a/app/src/components/approvals/bot-rules.tsx b/app/src/components/approvals/bot-rules.tsx index c541694d70..7023a1752e 100644 --- a/app/src/components/approvals/bot-rules.tsx +++ b/app/src/components/approvals/bot-rules.tsx @@ -1,4 +1,4 @@ -import { IconChecklist } from "@tabler/icons-react"; +import { IconChecklist } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/approvals/conversation-allowances.tsx b/app/src/components/approvals/conversation-allowances.tsx index 3c5fcbd84d..61bc097fcf 100644 --- a/app/src/components/approvals/conversation-allowances.tsx +++ b/app/src/components/approvals/conversation-allowances.tsx @@ -1,5 +1,5 @@ import { approvalPhrase } from "@openbot/shared/tool-name"; -import { IconCircleCheck } from "@tabler/icons-react"; +import { IconCircleCheck } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/approvals/describe-rules.tsx b/app/src/components/approvals/describe-rules.tsx index 9587987115..d578e4d370 100644 --- a/app/src/components/approvals/describe-rules.tsx +++ b/app/src/components/approvals/describe-rules.tsx @@ -6,7 +6,7 @@ import { IconPlus, IconTrash, IconUsers, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type UseQueryResult, useQuery } from "@tanstack/react-query"; import type { AuditEvent } from "@/components/audit/audit-cells"; import { diff --git a/app/src/components/approvals/question-notice.tsx b/app/src/components/approvals/question-notice.tsx index 19419cb57c..1314e4e5f0 100644 --- a/app/src/components/approvals/question-notice.tsx +++ b/app/src/components/approvals/question-notice.tsx @@ -1,5 +1,5 @@ import type { Message } from "@ag-ui/core"; -import { IconX } from "@tabler/icons-react"; +import { IconX } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { BotOrb } from "@/components/agents/bot-orb"; diff --git a/app/src/components/approvals/rules.tsx b/app/src/components/approvals/rules.tsx index c974807c22..f4415d5e3d 100644 --- a/app/src/components/approvals/rules.tsx +++ b/app/src/components/approvals/rules.tsx @@ -4,7 +4,7 @@ import { IconLock, IconPlus, IconShieldCheck, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type UseMutationResult, useQuery } from "@tanstack/react-query"; import { useId, useState } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/approvals/settings.tsx b/app/src/components/approvals/settings.tsx index 7527bdeebe..2726697547 100644 --- a/app/src/components/approvals/settings.tsx +++ b/app/src/components/approvals/settings.tsx @@ -3,7 +3,7 @@ import { IconEyeCheck, IconHandStop, IconTerminal2, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/approvals/shared-use-requests.tsx b/app/src/components/approvals/shared-use-requests.tsx index 470bbb639b..a9389575a8 100644 --- a/app/src/components/approvals/shared-use-requests.tsx +++ b/app/src/components/approvals/shared-use-requests.tsx @@ -1,4 +1,4 @@ -import { IconShare } from "@tabler/icons-react"; +import { IconShare } from "@/components/icons"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Fragment } from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/approvals/team-settings.tsx b/app/src/components/approvals/team-settings.tsx index 688a1b36fd..139936d150 100644 --- a/app/src/components/approvals/team-settings.tsx +++ b/app/src/components/approvals/team-settings.tsx @@ -13,7 +13,7 @@ import { IconTerminal2, IconTrash, IconUserCog, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/approvals/waiting.tsx b/app/src/components/approvals/waiting.tsx index 0ea2b74a35..5865b54be2 100644 --- a/app/src/components/approvals/waiting.tsx +++ b/app/src/components/approvals/waiting.tsx @@ -9,7 +9,7 @@ import { IconHandStop, IconMessageQuestion, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { Fragment, type ReactNode, useState } from "react"; diff --git a/app/src/components/audit/ask-the-trail.tsx b/app/src/components/audit/ask-the-trail.tsx index 406ddd97f0..cabe9dfcfd 100644 --- a/app/src/components/audit/ask-the-trail.tsx +++ b/app/src/components/audit/ask-the-trail.tsx @@ -3,7 +3,7 @@ import { IconFilter, IconInfoCircle, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useState } from "react"; import { InputGroup, diff --git a/app/src/components/audit/audit-filters.tsx b/app/src/components/audit/audit-filters.tsx index db542fb154..df0948764f 100644 --- a/app/src/components/audit/audit-filters.tsx +++ b/app/src/components/audit/audit-filters.tsx @@ -10,7 +10,7 @@ import { } from "@openbot/shared/audit-filters"; import { auditTypeWords } from "@openbot/shared/audit-words"; import { connectorName, humanise } from "@openbot/shared/tool-name"; -import { IconChevronDown, IconCirclePlus, IconX } from "@tabler/icons-react"; +import { IconChevronDown, IconCirclePlus, IconX } from "@/components/icons"; import { type ReactElement, type ReactNode, useState } from "react"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/audit/audit-table.tsx b/app/src/components/audit/audit-table.tsx index a55e56f1d1..6325a6c7dd 100644 --- a/app/src/components/audit/audit-table.tsx +++ b/app/src/components/audit/audit-table.tsx @@ -3,7 +3,7 @@ import { IconArrowUp, IconCirclePlus, IconSearch, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type ColumnDef, diff --git a/app/src/components/auth/cloud-sign-in.tsx b/app/src/components/auth/cloud-sign-in.tsx index 275dcdd5c2..bb8bd7bb7a 100644 --- a/app/src/components/auth/cloud-sign-in.tsx +++ b/app/src/components/auth/cloud-sign-in.tsx @@ -1,4 +1,4 @@ -import { IconBuilding, IconChevronRight } from "@tabler/icons-react"; +import { IconBuilding, IconChevronRight } from "@/components/icons"; import { useEffect, useRef, useState } from "react"; import { Trademark } from "@/components/edition/brand-name"; import { diff --git a/app/src/components/auth/company-sign-in-page.tsx b/app/src/components/auth/company-sign-in-page.tsx index c1e96d3a83..866c6c42ac 100644 --- a/app/src/components/auth/company-sign-in-page.tsx +++ b/app/src/components/auth/company-sign-in-page.tsx @@ -2,7 +2,7 @@ import { IconBuilding, IconChevronDown, IconUserCircle, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { type ReactNode, useSyncExternalStore } from "react"; import AgentOrb from "@/components/agents/orb/agent-orb"; diff --git a/app/src/components/bot-profile/access.tsx b/app/src/components/bot-profile/access.tsx index a73a815d93..1387389935 100644 --- a/app/src/components/bot-profile/access.tsx +++ b/app/src/components/bot-profile/access.tsx @@ -4,7 +4,7 @@ import { IconChevronRight, IconPlug, IconPlus, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/bot-profile/activity.tsx b/app/src/components/bot-profile/activity.tsx index ac29593487..50cf7e98d0 100644 --- a/app/src/components/bot-profile/activity.tsx +++ b/app/src/components/bot-profile/activity.tsx @@ -10,7 +10,7 @@ import { IconHistory, IconListDetails, IconTargetArrow, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/bot-profile/default-model.tsx b/app/src/components/bot-profile/default-model.tsx index 1c52c919cc..c155bdd5b3 100644 --- a/app/src/components/bot-profile/default-model.tsx +++ b/app/src/components/bot-profile/default-model.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconCpu } from "@tabler/icons-react"; +import { IconChevronRight, IconCpu } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { useId, useState } from "react"; import { ModelPicker } from "@/components/channels/composer/model-picker"; diff --git a/app/src/components/bot-profile/manage.tsx b/app/src/components/bot-profile/manage.tsx index b332a497ef..361d426109 100644 --- a/app/src/components/bot-profile/manage.tsx +++ b/app/src/components/bot-profile/manage.tsx @@ -5,7 +5,7 @@ import { IconPin, IconRefresh, IconTrash, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/bot-profile/pause-banner.tsx b/app/src/components/bot-profile/pause-banner.tsx index 3575be2f52..905465fbdb 100644 --- a/app/src/components/bot-profile/pause-banner.tsx +++ b/app/src/components/bot-profile/pause-banner.tsx @@ -1,4 +1,4 @@ -import { IconPlayerPause } from "@tabler/icons-react"; +import { IconPlayerPause } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { setBotPausedMutationOptions } from "@/lib/bot-lifecycle/mutations"; diff --git a/app/src/components/bot-profile/profile.tsx b/app/src/components/bot-profile/profile.tsx index fc4ea94e37..fed4217fbf 100644 --- a/app/src/components/bot-profile/profile.tsx +++ b/app/src/components/bot-profile/profile.tsx @@ -3,7 +3,7 @@ import { IconChevronRight, IconMessage, IconPlayerPause, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import type * as React from "react"; diff --git a/app/src/components/bot-profile/settings-rows.tsx b/app/src/components/bot-profile/settings-rows.tsx index ef8ed23cc6..399ea3bf0a 100644 --- a/app/src/components/bot-profile/settings-rows.tsx +++ b/app/src/components/bot-profile/settings-rows.tsx @@ -2,7 +2,7 @@ import { IconChevronRight, IconDeviceMobile, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; diff --git a/app/src/components/bot-profile/setup.tsx b/app/src/components/bot-profile/setup.tsx index c350b1708d..3d47ab7059 100644 --- a/app/src/components/bot-profile/setup.tsx +++ b/app/src/components/bot-profile/setup.tsx @@ -8,7 +8,7 @@ import { IconShieldCheck, IconTag, IconTextCaption, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useId, useState } from "react"; import type { ZodType } from "zod"; diff --git a/app/src/components/bot-profile/sharing.tsx b/app/src/components/bot-profile/sharing.tsx index 2b5e9b4b52..35daf275b4 100644 --- a/app/src/components/bot-profile/sharing.tsx +++ b/app/src/components/bot-profile/sharing.tsx @@ -6,7 +6,7 @@ import { IconUsers, IconUsersGroup, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useId, useState } from "react"; import { diff --git a/app/src/components/bots/bot-roster.tsx b/app/src/components/bots/bot-roster.tsx index c282a1f6bd..09f211ed50 100644 --- a/app/src/components/bots/bot-roster.tsx +++ b/app/src/components/bots/bot-roster.tsx @@ -1,4 +1,4 @@ -import { IconBolt, IconChevronRight, IconPlus } from "@tabler/icons-react"; +import { IconBolt, IconChevronRight, IconPlus } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment, useState } from "react"; diff --git a/app/src/components/boundaries/dry-run-changes.tsx b/app/src/components/boundaries/dry-run-changes.tsx index 2acd00c9be..4ccb323de7 100644 --- a/app/src/components/boundaries/dry-run-changes.tsx +++ b/app/src/components/boundaries/dry-run-changes.tsx @@ -1,4 +1,4 @@ -import { IconDeviceDesktop, IconPlug } from "@tabler/icons-react"; +import { IconDeviceDesktop, IconPlug } from "@/components/icons"; import type { ReactNode } from "react"; import { type AuditEvent, diff --git a/app/src/components/boundaries/rule-reading.tsx b/app/src/components/boundaries/rule-reading.tsx index 52c2ab6ee3..449c81893e 100644 --- a/app/src/components/boundaries/rule-reading.tsx +++ b/app/src/components/boundaries/rule-reading.tsx @@ -1,4 +1,4 @@ -import { IconAlertTriangle, IconCircleCheck } from "@tabler/icons-react"; +import { IconAlertTriangle, IconCircleCheck } from "@/components/icons"; import type { WrittenRule } from "@/components/boundaries/describe-rule"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/browser/browser-bar.tsx b/app/src/components/browser/browser-bar.tsx index c110bdac2b..e0641131ac 100644 --- a/app/src/components/browser/browser-bar.tsx +++ b/app/src/components/browser/browser-bar.tsx @@ -8,7 +8,7 @@ import { IconReload, IconWorld, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import type { UseMutationResult } from "@tanstack/react-query"; import { type KeyboardEvent, diff --git a/app/src/components/browser/browser-screen.tsx b/app/src/components/browser/browser-screen.tsx index 71d75b2987..e28120eb99 100644 --- a/app/src/components/browser/browser-screen.tsx +++ b/app/src/components/browser/browser-screen.tsx @@ -1,5 +1,5 @@ import type { BrowserApiState } from "@openbot/shared/openbot-browser"; -import { IconSearch } from "@tabler/icons-react"; +import { IconSearch } from "@/components/icons"; import { useMutation } from "@tanstack/react-query"; import { type ReactNode, type RefObject, useId, useRef, useState } from "react"; import { ComputerBlocked } from "@/components/computer/computer-blocked"; diff --git a/app/src/components/browser/learning-next.tsx b/app/src/components/browser/learning-next.tsx index 218d93ad81..643649c100 100644 --- a/app/src/components/browser/learning-next.tsx +++ b/app/src/components/browser/learning-next.tsx @@ -2,7 +2,7 @@ import { IconAlertTriangle, IconLoader2, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { type ReactNode, useEffect, useRef, useState } from "react"; diff --git a/app/src/components/browser/narration-choice.tsx b/app/src/components/browser/narration-choice.tsx index 1b8ce4aaca..3451fbe04e 100644 --- a/app/src/components/browser/narration-choice.tsx +++ b/app/src/components/browser/narration-choice.tsx @@ -1,5 +1,5 @@ import type { NarrationPreference } from "@openbot/shared/user-preferences"; -import { IconMicrophone } from "@tabler/icons-react"; +import { IconMicrophone } from "@/components/icons"; import { useMutation } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/browser/narration.tsx b/app/src/components/browser/narration.tsx index ba9ee5b9d6..bb9b837d8c 100644 --- a/app/src/components/browser/narration.tsx +++ b/app/src/components/browser/narration.tsx @@ -3,7 +3,7 @@ import { IconInfoCircle, IconMicrophone, IconMicrophoneOff, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useId } from "react"; import { Item, diff --git a/app/src/components/browser/recording.tsx b/app/src/components/browser/recording.tsx index 1cb5210733..f997a4f38a 100644 --- a/app/src/components/browser/recording.tsx +++ b/app/src/components/browser/recording.tsx @@ -8,7 +8,7 @@ import { IconLoader2, IconPlayerRecordFilled, IconTrash, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type UseMutationOptions, useMutation } from "@tanstack/react-query"; import { type ReactNode, useRef, useState } from "react"; import { Button, buttonVariants } from "@/components/ui/button"; diff --git a/app/src/components/browser/teach-steps.tsx b/app/src/components/browser/teach-steps.tsx index 7d294f25e5..652e49309b 100644 --- a/app/src/components/browser/teach-steps.tsx +++ b/app/src/components/browser/teach-steps.tsx @@ -1,5 +1,5 @@ import type { BrowserApiState } from "@openbot/shared/openbot-browser"; -import { IconArrowLeft, IconPlayerRecordFilled } from "@tabler/icons-react"; +import { IconArrowLeft, IconPlayerRecordFilled } from "@/components/icons"; import { useMutation } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { type ReactNode, useEffect, useState } from "react"; diff --git a/app/src/components/browser/your-recordings.tsx b/app/src/components/browser/your-recordings.tsx index 1ed740b4fb..bcca24e767 100644 --- a/app/src/components/browser/your-recordings.tsx +++ b/app/src/components/browser/your-recordings.tsx @@ -1,6 +1,6 @@ import type { LauncherState } from "@openbot/shared/openbot-browser"; import type { RecordingRow } from "@openbot/shared/recorder-api"; -import { IconVideo } from "@tabler/icons-react"; +import { IconVideo } from "@/components/icons"; import { useInfiniteQuery } from "@tanstack/react-query"; import React, { type ReactNode } from "react"; import { diff --git a/app/src/components/channels/attachment-view.tsx b/app/src/components/channels/attachment-view.tsx index 00ec4b7223..7302842502 100644 --- a/app/src/components/channels/attachment-view.tsx +++ b/app/src/components/channels/attachment-view.tsx @@ -1,4 +1,4 @@ -import { IconAlertTriangle, IconX } from "@tabler/icons-react"; +import { IconAlertTriangle, IconX } from "@/components/icons"; import { useEffect, useState } from "react"; import { Dialog, diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index 6873019dc4..e92073b25c 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -35,7 +35,7 @@ import { IconClock, IconDownload, IconPhoto, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { QueryClientContext, useQuery } from "@tanstack/react-query"; import { motion, useReducedMotion } from "motion/react"; import { diff --git a/app/src/components/channels/coding-tool-cards.tsx b/app/src/components/channels/coding-tool-cards.tsx index 7f66a4f49d..e6149e796b 100644 --- a/app/src/components/channels/coding-tool-cards.tsx +++ b/app/src/components/channels/coding-tool-cards.tsx @@ -8,7 +8,7 @@ import { IconPencil, IconSearch, IconTerminal2, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { structuredPatch } from "diff"; import { type ReactNode, useState } from "react"; import { Badge, GalleryFrame } from "@/components/gallery/frame"; diff --git a/app/src/components/channels/composer/attachment-strip.tsx b/app/src/components/channels/composer/attachment-strip.tsx index 5bbf9dee51..d35762a47a 100644 --- a/app/src/components/channels/composer/attachment-strip.tsx +++ b/app/src/components/channels/composer/attachment-strip.tsx @@ -1,4 +1,4 @@ -import { IconPhoto, IconX } from "@tabler/icons-react"; +import { IconPhoto, IconX } from "@/components/icons"; import { motion, useReducedMotion } from "motion/react"; import { useState } from "react"; diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index 46246b4d4d..89679ad0d2 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -8,7 +8,7 @@ import { IconLoader2, IconPlayerStopFilled, IconPlus, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { PromptArea, type PromptAreaHandle } from "prompt-area"; import { isSegmentsEmpty, diff --git a/app/src/components/channels/composer/dictation-controls.tsx b/app/src/components/channels/composer/dictation-controls.tsx index e11d8bfe81..c2227434f7 100644 --- a/app/src/components/channels/composer/dictation-controls.tsx +++ b/app/src/components/channels/composer/dictation-controls.tsx @@ -4,7 +4,7 @@ import { IconMicrophone, IconPlayerStopFilled, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { motion, useReducedMotion } from "motion/react"; import { type ReactNode, useEffect, useRef } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/channels/composer/model-picker.tsx b/app/src/components/channels/composer/model-picker.tsx index a4ee8e51ff..fb134c2599 100644 --- a/app/src/components/channels/composer/model-picker.tsx +++ b/app/src/components/channels/composer/model-picker.tsx @@ -7,7 +7,7 @@ import { IconCpu, IconCube, IconPlus, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMemo, useRef, useState } from "react"; import { HarnessMark } from "@/components/agents/harness-mark"; import { reconnectPath } from "@/components/channels/stopped-connection-notice"; diff --git a/app/src/components/channels/composer/rejected-files.tsx b/app/src/components/channels/composer/rejected-files.tsx index ee0c1513a8..89c89068d2 100644 --- a/app/src/components/channels/composer/rejected-files.tsx +++ b/app/src/components/channels/composer/rejected-files.tsx @@ -1,4 +1,4 @@ -import { IconX } from "@tabler/icons-react"; +import { IconX } from "@/components/icons"; import { Collapse } from "./collapse"; diff --git a/app/src/components/channels/conversation-actions.tsx b/app/src/components/channels/conversation-actions.tsx index 974f81dcd5..b639d20df3 100644 --- a/app/src/components/channels/conversation-actions.tsx +++ b/app/src/components/channels/conversation-actions.tsx @@ -1,4 +1,4 @@ -import { IconPin, IconPinnedOff, IconTrash } from "@tabler/icons-react"; +import { IconPin, IconPinnedOff, IconTrash } from "@/components/icons"; import { useInfiniteQuery, useMutation, diff --git a/app/src/components/channels/file-icon.tsx b/app/src/components/channels/file-icon.tsx index 78de28cced..e2d25f7b6d 100644 --- a/app/src/components/channels/file-icon.tsx +++ b/app/src/components/channels/file-icon.tsx @@ -9,8 +9,8 @@ import { IconJson, IconMarkdown, IconPhoto, - type TablerIcon, -} from "@tabler/icons-react"; + type Icon, +} from "@/components/icons"; import { type AcceptedFileType, mediaTypeOf, @@ -37,7 +37,7 @@ export const FILE_TYPE_ICONS = { "text/markdown": IconMarkdown, "text/csv": IconFileTypeCsv, "application/json": IconJson, -} as const satisfies Record; +} as const satisfies Record; /** A file's icon by the type the server found in it; the plain file icon for a type not known. */ export function FileTypeIcon({ diff --git a/app/src/components/channels/generated-image-card.tsx b/app/src/components/channels/generated-image-card.tsx index 5df41b40c0..a1b12b815c 100644 --- a/app/src/components/channels/generated-image-card.tsx +++ b/app/src/components/channels/generated-image-card.tsx @@ -2,6 +2,8 @@ import type { GenerateImageResult, ImageAspect, } from "@openbot/shared/generate-image"; +import { useReducedMotion } from "motion/react"; +import { type CSSProperties, useCallback, useEffect, useState } from "react"; import { IconAlertTriangle, IconDownload, @@ -9,9 +11,7 @@ import { IconPhotoAi, IconPhotoOff, IconSparkles, -} from "@tabler/icons-react"; -import { useReducedMotion } from "motion/react"; -import { type CSSProperties, useCallback, useEffect, useState } from "react"; +} from "@/components/icons"; import { Button } from "@/components/ui/button"; import { attachmentAddress } from "@/lib/channels/attachments"; import { fileSize } from "@/lib/computers/sent-file"; diff --git a/app/src/components/channels/group-people.tsx b/app/src/components/channels/group-people.tsx index 5f5012bc0c..51848c4e56 100644 --- a/app/src/components/channels/group-people.tsx +++ b/app/src/components/channels/group-people.tsx @@ -1,4 +1,4 @@ -import { IconUser, IconUsers } from "@tabler/icons-react"; +import { IconUser, IconUsers } from "@/components/icons"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Fragment, useState } from "react"; import { PeopleTypeahead } from "@/components/teams/people-typeahead"; diff --git a/app/src/components/channels/research-results.tsx b/app/src/components/channels/research-results.tsx index 580aed570a..9274df8c01 100644 --- a/app/src/components/channels/research-results.tsx +++ b/app/src/components/channels/research-results.tsx @@ -1,4 +1,4 @@ -import { IconArrowUpRight, IconWorld } from "@tabler/icons-react"; +import { IconArrowUpRight, IconWorld } from "@/components/icons"; import { useState } from "react"; import type { ResearchSource } from "@/lib/plugins/research-results"; diff --git a/app/src/components/channels/sent-file-card.tsx b/app/src/components/channels/sent-file-card.tsx index 299df7f1db..20bfb1aee1 100644 --- a/app/src/components/channels/sent-file-card.tsx +++ b/app/src/components/channels/sent-file-card.tsx @@ -1,4 +1,4 @@ -import { IconAlertTriangle, IconDownload } from "@tabler/icons-react"; +import { IconAlertTriangle, IconDownload } from "@/components/icons"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { attachmentAddress } from "@/lib/channels/attachments"; diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 80b751fcfa..12b8924a20 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -30,7 +30,7 @@ import { IconTerminal2, IconTool, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type ReactNode, useCallback, diff --git a/app/src/components/channels/voice-call-widget.tsx b/app/src/components/channels/voice-call-widget.tsx index a42ab76d0a..cd926869f7 100644 --- a/app/src/components/channels/voice-call-widget.tsx +++ b/app/src/components/channels/voice-call-widget.tsx @@ -5,7 +5,7 @@ import { IconMicrophoneOff, IconSettings, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; diff --git a/app/src/components/channels/voice-chat-card.tsx b/app/src/components/channels/voice-chat-card.tsx index 9710b6c11c..db002b21dc 100644 --- a/app/src/components/channels/voice-chat-card.tsx +++ b/app/src/components/channels/voice-chat-card.tsx @@ -1,4 +1,4 @@ -import { IconChevronDown, IconLoader2 } from "@tabler/icons-react"; +import { IconChevronDown, IconLoader2 } from "@/components/icons"; import { IconWaveform } from "@/components/icons/waveform"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/computer/activity-log.tsx b/app/src/components/computer/activity-log.tsx index 8420b37f8d..0ac07e3459 100644 --- a/app/src/components/computer/activity-log.tsx +++ b/app/src/components/computer/activity-log.tsx @@ -25,7 +25,7 @@ import { IconSend, IconTerminal2, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useSyncExternalStore } from "react"; import { type AllowedDecision, diff --git a/app/src/components/computer/bot-browser.tsx b/app/src/components/computer/bot-browser.tsx index 0242faa6bf..3f4ceaac41 100644 --- a/app/src/components/computer/bot-browser.tsx +++ b/app/src/components/computer/bot-browser.tsx @@ -1,6 +1,6 @@ import type { BotBrowserApiState } from "@openbot/shared/bot-browser"; import { RECORDER_COLLECTS_SHORT } from "@openbot/shared/recorder-disclosure"; -import { IconLock, IconPlayerStop } from "@tabler/icons-react"; +import { IconLock, IconPlayerStop } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { type ReactNode, useId } from "react"; import { diff --git a/app/src/components/computer/computer-blocked.tsx b/app/src/components/computer/computer-blocked.tsx index 0c305575a6..9657b33ff4 100644 --- a/app/src/components/computer/computer-blocked.tsx +++ b/app/src/components/computer/computer-blocked.tsx @@ -1,4 +1,4 @@ -import { IconDeviceDesktopOff } from "@tabler/icons-react"; +import { IconDeviceDesktopOff } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { buttonVariants } from "@/components/ui/button"; diff --git a/app/src/components/computer/computer-controls.tsx b/app/src/components/computer/computer-controls.tsx index fe87b1ce53..34c4f778f6 100644 --- a/app/src/components/computer/computer-controls.tsx +++ b/app/src/components/computer/computer-controls.tsx @@ -1,4 +1,4 @@ -import { IconDeviceDesktop } from "@tabler/icons-react"; +import { IconDeviceDesktop } from "@/components/icons"; import { useEffect, useRef } from "react"; import { Button } from "@/components/ui/button"; import { useComputerControl } from "@/lib/computers/use-control"; diff --git a/app/src/components/computer/computer-panel.tsx b/app/src/components/computer/computer-panel.tsx index a8d1af2ce5..d82a38f3ed 100644 --- a/app/src/components/computer/computer-panel.tsx +++ b/app/src/components/computer/computer-panel.tsx @@ -1,11 +1,11 @@ +import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; +import { useEffect, useState, useSyncExternalStore } from "react"; import { IconDeviceDesktop, IconDeviceDesktopOff, IconTerminal2, -} from "@tabler/icons-react"; -import { useQuery } from "@tanstack/react-query"; -import { useEffect, useState, useSyncExternalStore } from "react"; +} from "@/components/icons"; import { PageEmpty } from "@/components/layout/page-parts"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { WindowsComputerView } from "@/components/windows-computer/windows-computer-page"; diff --git a/app/src/components/computer/computer-starting.tsx b/app/src/components/computer/computer-starting.tsx index 1f540c6b0c..39886a0dfb 100644 --- a/app/src/components/computer/computer-starting.tsx +++ b/app/src/components/computer/computer-starting.tsx @@ -1,9 +1,9 @@ +import { useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; import { IconDeviceDesktop, IconDeviceDesktopExclamation, -} from "@tabler/icons-react"; -import { useQuery } from "@tanstack/react-query"; -import { Link } from "@tanstack/react-router"; +} from "@/components/icons"; import { Button, buttonVariants } from "@/components/ui/button"; import { Empty, diff --git a/app/src/components/computer/computer-view.tsx b/app/src/components/computer/computer-view.tsx index a2a827dd6a..c6f53dfbac 100644 --- a/app/src/components/computer/computer-view.tsx +++ b/app/src/components/computer/computer-view.tsx @@ -1,7 +1,7 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import type { BotBrowserApiState } from "@openbot/shared/bot-browser"; import { COMPUTER_START_WAIT_MS } from "@openbot/shared/computer-start"; -import { IconLock, IconWorld, IconX } from "@tabler/icons-react"; +import { IconLock, IconWorld, IconX } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type CSSProperties, diff --git a/app/src/components/computer/desktop-illustration.tsx b/app/src/components/computer/desktop-illustration.tsx index d93188d814..45dd30cdf3 100644 --- a/app/src/components/computer/desktop-illustration.tsx +++ b/app/src/components/computer/desktop-illustration.tsx @@ -1,4 +1,4 @@ -import { IconFolderFilled, IconLock } from "@tabler/icons-react"; +import { IconFolderFilled, IconLock } from "@/components/icons"; import { motion, useReducedMotion } from "motion/react"; import { EASE_OUT } from "@/lib/motion"; import { cn } from "@/lib/utils"; @@ -121,7 +121,7 @@ function PointerCursor({ still }: { still: boolean }) { scale: { ...TOUR, ease: [...CLICK_EASE] }, }} > - {/* Tabler's pointer-2, inlined: the installed icon package predates it. */} + {/* Tabler's pointer-2, inlined: the illustration's pointer, not one of the app's icons. */} >; - icon?: TablerIcon; + icon?: Icon; /** What the rows are about, drawn over them: the app a Bot's actions are in. */ lead?: ReactNode; /** Null while it runs, or when it was refused before a change was worked out. */ diff --git a/app/src/components/settings-tools/settings-read-card.tsx b/app/src/components/settings-tools/settings-read-card.tsx index 734621984d..3367d5ab88 100644 --- a/app/src/components/settings-tools/settings-read-card.tsx +++ b/app/src/components/settings-tools/settings-read-card.tsx @@ -1,4 +1,4 @@ -import { IconSettings, type TablerIcon } from "@tabler/icons-react"; +import { IconSettings, type Icon } from "@/components/icons"; import type { ReactNode } from "react"; import { cn } from "@/lib/utils"; import type { SettingsToolCallState } from "./registry"; @@ -27,7 +27,7 @@ export function SettingsReadCard({ wrapTitle?: boolean; /** One line under the title. */ caption?: string; - icon?: TablerIcon; + icon?: Icon; state: SettingsToolCallState; /** Why it was refused or didn't work, in the person's words. */ reason?: string; diff --git a/app/src/components/settings-tools/update-bot-apps-card.tsx b/app/src/components/settings-tools/update-bot-apps-card.tsx index 7658e023d6..c35fca1aae 100644 --- a/app/src/components/settings-tools/update-bot-apps-card.tsx +++ b/app/src/components/settings-tools/update-bot-apps-card.tsx @@ -1,5 +1,5 @@ import { appToolName, connectorName } from "@openbot/shared/tool-name"; -import { IconRobot } from "@tabler/icons-react"; +import { IconRobot } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { PluginLogo } from "@/components/plugins/plugin-logo"; import { agentListQueryOptions } from "@/lib/agents/queries"; diff --git a/app/src/components/settings-tools/update-my-bot-card.tsx b/app/src/components/settings-tools/update-my-bot-card.tsx index 21fb2195ad..37de1156b0 100644 --- a/app/src/components/settings-tools/update-my-bot-card.tsx +++ b/app/src/components/settings-tools/update-my-bot-card.tsx @@ -1,4 +1,4 @@ -import { IconRobot } from "@tabler/icons-react"; +import { IconRobot } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { agentListQueryOptions } from "@/lib/agents/queries"; import type { SettingsToolCardProps } from "./registry"; diff --git a/app/src/components/settings-tools/update-my-settings-card.tsx b/app/src/components/settings-tools/update-my-settings-card.tsx index a1d03a71dc..ae47578749 100644 --- a/app/src/components/settings-tools/update-my-settings-card.tsx +++ b/app/src/components/settings-tools/update-my-settings-card.tsx @@ -2,8 +2,8 @@ import { IconBell, IconListCheck, IconSettings, - type TablerIcon, -} from "@tabler/icons-react"; + type Icon, +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { agentListQueryOptions } from "@/lib/agents/queries"; import type { SettingsToolCardProps } from "./registry"; @@ -31,7 +31,7 @@ type Snapshot = { /** The screen the change lives on, with its title and icon, from what the call named. */ export function settingsScreenOf(after: unknown): { title: string; - icon: TablerIcon; + icon: Icon; link: SettingsScreenLink; } { const named = (after && typeof after === "object" ? after : {}) as Snapshot; diff --git a/app/src/components/settings-tools/update-organization-settings-card.tsx b/app/src/components/settings-tools/update-organization-settings-card.tsx index 9824911ca7..f8f1293b13 100644 --- a/app/src/components/settings-tools/update-organization-settings-card.tsx +++ b/app/src/components/settings-tools/update-organization-settings-card.tsx @@ -1,7 +1,4 @@ -import { - IconAdjustmentsHorizontal, - IconToggleRight, -} from "@tabler/icons-react"; +import { IconAdjustmentsHorizontal, IconToggleRight } from "@/components/icons"; import { type AdminCardState, AdminChangeCard, diff --git a/app/src/components/settings-tools/where-do-i-change-card.tsx b/app/src/components/settings-tools/where-do-i-change-card.tsx index 9f0bd62e75..fa1ab5d797 100644 --- a/app/src/components/settings-tools/where-do-i-change-card.tsx +++ b/app/src/components/settings-tools/where-do-i-change-card.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconCompass } from "@tabler/icons-react"; +import { IconChevronRight, IconCompass } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import type { SettingsToolCardProps } from "./registry"; import { SettingsReadCard } from "./settings-read-card"; diff --git a/app/src/components/settings/ai-connection-chooser.tsx b/app/src/components/settings/ai-connection-chooser.tsx index 77d258114d..8d90dc38b8 100644 --- a/app/src/components/settings/ai-connection-chooser.tsx +++ b/app/src/components/settings/ai-connection-chooser.tsx @@ -5,7 +5,7 @@ import { IconCloud, IconExternalLink, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createContext, diff --git a/app/src/components/settings/ai-connection-list.tsx b/app/src/components/settings/ai-connection-list.tsx index 150f5683ea..d8e3dc4872 100644 --- a/app/src/components/settings/ai-connection-list.tsx +++ b/app/src/components/settings/ai-connection-list.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconPlus } from "@tabler/icons-react"; +import { IconChevronRight, IconPlus } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; import { PageRows } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/ai-connection.tsx b/app/src/components/settings/ai-connection.tsx index 22e410747f..6bc525476b 100644 --- a/app/src/components/settings/ai-connection.tsx +++ b/app/src/components/settings/ai-connection.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconSparkles } from "@tabler/icons-react"; +import { IconChevronRight, IconSparkles } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/api-keys.tsx b/app/src/components/settings/api-keys.tsx index 8a7c1a8ef8..5eb0d317ce 100644 --- a/app/src/components/settings/api-keys.tsx +++ b/app/src/components/settings/api-keys.tsx @@ -1,4 +1,4 @@ -import { IconExternalLink, IconKey, IconPlus } from "@tabler/icons-react"; +import { IconExternalLink, IconKey, IconPlus } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useState } from "react"; import { diff --git a/app/src/components/settings/browser-notifications.tsx b/app/src/components/settings/browser-notifications.tsx index 55e7f7f4f7..f4bac22444 100644 --- a/app/src/components/settings/browser-notifications.tsx +++ b/app/src/components/settings/browser-notifications.tsx @@ -1,4 +1,4 @@ -import { IconBell } from "@tabler/icons-react"; +import { IconBell } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { diff --git a/app/src/components/settings/browsers/connected-browsers.tsx b/app/src/components/settings/browsers/connected-browsers.tsx index 7a19e22aa3..1eb4a98b4b 100644 --- a/app/src/components/settings/browsers/connected-browsers.tsx +++ b/app/src/components/settings/browsers/connected-browsers.tsx @@ -1,5 +1,5 @@ import type { ListedRecorderConnection } from "@openbot/shared/recorder-api"; -import { IconBrowser } from "@tabler/icons-react"; +import { IconBrowser } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useState } from "react"; import { diff --git a/app/src/components/settings/browsers/this-browser.tsx b/app/src/components/settings/browsers/this-browser.tsx index 81e81fc81f..4d4e3efe3b 100644 --- a/app/src/components/settings/browsers/this-browser.tsx +++ b/app/src/components/settings/browsers/this-browser.tsx @@ -1,4 +1,4 @@ -import { IconBrowser } from "@tabler/icons-react"; +import { IconBrowser } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type ReactNode, useEffect, useState } from "react"; import { noteStoreTabOpened } from "@/components/browser/browser-nav-item"; diff --git a/app/src/components/settings/chatgpt-browser-sign-in.tsx b/app/src/components/settings/chatgpt-browser-sign-in.tsx index 1b9d42f604..4ccde51b03 100644 --- a/app/src/components/settings/chatgpt-browser-sign-in.tsx +++ b/app/src/components/settings/chatgpt-browser-sign-in.tsx @@ -2,7 +2,7 @@ import { IconClipboard, IconExternalLink, IconMoodSad, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { type ClipboardEvent, useEffect, useRef, useState } from "react"; import { IllustrationFrame } from "@/components/onboarding/illustration-frame"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/settings/check-ins.tsx b/app/src/components/settings/check-ins.tsx index 2c347b3dd9..06aa7f6827 100644 --- a/app/src/components/settings/check-ins.tsx +++ b/app/src/components/settings/check-ins.tsx @@ -1,4 +1,4 @@ -import { IconRadar } from "@tabler/icons-react"; +import { IconRadar } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { diff --git a/app/src/components/settings/company-sign-in.tsx b/app/src/components/settings/company-sign-in.tsx index 33d49ea261..7505c8af68 100644 --- a/app/src/components/settings/company-sign-in.tsx +++ b/app/src/components/settings/company-sign-in.tsx @@ -1,4 +1,4 @@ -import { IconBuildingBank } from "@tabler/icons-react"; +import { IconBuildingBank } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { LinkCompanyAccount } from "@/components/auth/link-company-account"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/connection-sections.tsx b/app/src/components/settings/connection-sections.tsx index eeddcb8a14..ee261f22bf 100644 --- a/app/src/components/settings/connection-sections.tsx +++ b/app/src/components/settings/connection-sections.tsx @@ -7,7 +7,7 @@ import { IconPlugConnected, IconShieldCheck, IconUserCircle, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/delete-account.tsx b/app/src/components/settings/delete-account.tsx index b0a1362e77..2d4e278c7a 100644 --- a/app/src/components/settings/delete-account.tsx +++ b/app/src/components/settings/delete-account.tsx @@ -1,4 +1,4 @@ -import { IconArchive, IconBuilding, IconTrash } from "@tabler/icons-react"; +import { IconArchive, IconBuilding, IconTrash } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useNavigate, useRouter } from "@tanstack/react-router"; import { diff --git a/app/src/components/settings/devices.tsx b/app/src/components/settings/devices.tsx index d06ab953aa..1540cf813d 100644 --- a/app/src/components/settings/devices.tsx +++ b/app/src/components/settings/devices.tsx @@ -1,4 +1,4 @@ -import { IconDeviceMobile, IconDevices, IconSend } from "@tabler/icons-react"; +import { IconDeviceMobile, IconDevices, IconSend } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment } from "react"; import { diff --git a/app/src/components/settings/github-sources.tsx b/app/src/components/settings/github-sources.tsx index 1c15ae7a77..59574f374f 100644 --- a/app/src/components/settings/github-sources.tsx +++ b/app/src/components/settings/github-sources.tsx @@ -1,4 +1,4 @@ -import { IconBrandGithub, IconPlus } from "@tabler/icons-react"; +import { IconBrandGithub, IconPlus } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useId, useState } from "react"; import { diff --git a/app/src/components/settings/learning-review.tsx b/app/src/components/settings/learning-review.tsx index 2e2449e9e3..e783263988 100644 --- a/app/src/components/settings/learning-review.tsx +++ b/app/src/components/settings/learning-review.tsx @@ -1,5 +1,5 @@ import type { LearningProposal } from "@openbot/shared/learning"; -import { IconChevronRight, IconSparkles } from "@tabler/icons-react"; +import { IconChevronRight, IconSparkles } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment, useEffect, useRef, useState } from "react"; import { diff --git a/app/src/components/settings/learning-sharing.tsx b/app/src/components/settings/learning-sharing.tsx index 32106f8ec0..cc159451d1 100644 --- a/app/src/components/settings/learning-sharing.tsx +++ b/app/src/components/settings/learning-sharing.tsx @@ -6,7 +6,7 @@ import { IconLock, IconSparkles, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import React from "react"; import { diff --git a/app/src/components/settings/linked-accounts.test.tsx b/app/src/components/settings/linked-accounts.test.tsx index cd4ab94aea..9b69d25956 100644 --- a/app/src/components/settings/linked-accounts.test.tsx +++ b/app/src/components/settings/linked-accounts.test.tsx @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { IconBrandGithub, IconBrandSlack, IconLink } from "@tabler/icons-react"; +import { IconBrandGithub, IconBrandSlack, IconLink } from "@/components/icons"; import { ClientError } from "@/lib/client"; import { alreadyUnlinked } from "@/lib/identity/mutations"; import { linkedAccountsAbsent } from "@/lib/identity/queries"; diff --git a/app/src/components/settings/linked-accounts.tsx b/app/src/components/settings/linked-accounts.tsx index 078518b3dd..e398a3d0a0 100644 --- a/app/src/components/settings/linked-accounts.tsx +++ b/app/src/components/settings/linked-accounts.tsx @@ -1,4 +1,4 @@ -import { IconBrandGithub, IconBrandSlack, IconLink } from "@tabler/icons-react"; +import { IconBrandGithub, IconBrandSlack, IconLink } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { diff --git a/app/src/components/settings/message-list-preference.tsx b/app/src/components/settings/message-list-preference.tsx index e0992c1637..5d99239a0a 100644 --- a/app/src/components/settings/message-list-preference.tsx +++ b/app/src/components/settings/message-list-preference.tsx @@ -1,4 +1,4 @@ -import { IconLayoutList, IconLayoutSidebar } from "@tabler/icons-react"; +import { IconLayoutList, IconLayoutSidebar } from "@/components/icons"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { ChannelItemContent } from "@/components/app-sidebar/channel-item-content"; import { PageRows } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/profile.tsx b/app/src/components/settings/profile.tsx index 1f6919d14a..579dfe744c 100644 --- a/app/src/components/settings/profile.tsx +++ b/app/src/components/settings/profile.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconUserCircle } from "@tabler/icons-react"; +import { IconChevronRight, IconUserCircle } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useId, useState } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/settings/provider-pages.tsx b/app/src/components/settings/provider-pages.tsx index 4162115472..27e138c082 100644 --- a/app/src/components/settings/provider-pages.tsx +++ b/app/src/components/settings/provider-pages.tsx @@ -4,7 +4,7 @@ import { IconPlugConnectedX, IconSparkles, IconStar, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link, useNavigate } from "@tanstack/react-router"; import { type ComponentProps, Fragment, useState } from "react"; diff --git a/app/src/components/settings/settings-sidebar.tsx b/app/src/components/settings/settings-sidebar.tsx index 3acdb0da29..6c61fe26b4 100644 --- a/app/src/components/settings/settings-sidebar.tsx +++ b/app/src/components/settings/settings-sidebar.tsx @@ -7,7 +7,7 @@ import { IconLayoutGrid, IconListCheck, IconSettings, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { Link, type LinkOptions } from "@tanstack/react-router"; import type * as React from "react"; diff --git a/app/src/components/settings/standing-instructions.tsx b/app/src/components/settings/standing-instructions.tsx index 3f3b89163b..bab03fe1f8 100644 --- a/app/src/components/settings/standing-instructions.tsx +++ b/app/src/components/settings/standing-instructions.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconNotes } from "@tabler/icons-react"; +import { IconChevronRight, IconNotes } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/settings/star-on-github.tsx b/app/src/components/settings/star-on-github.tsx index 90cb39b10b..f1f0d98759 100644 --- a/app/src/components/settings/star-on-github.tsx +++ b/app/src/components/settings/star-on-github.tsx @@ -1,6 +1,6 @@ import { STAR_ON_GITHUB } from "@openbot/shared/notices"; -import { IconBrandGithub } from "@tabler/icons-react"; import { useMutation, useQuery } from "@tanstack/react-query"; +import { IconBrandGithub } from "@/components/icons"; import { OPENBOT_REPO_URL } from "@/components/star-prompt/star-prompt"; import { buttonVariants } from "@/components/ui/button"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; diff --git a/app/src/components/settings/theme-row.tsx b/app/src/components/settings/theme-row.tsx index 381073fb69..315022a9de 100644 --- a/app/src/components/settings/theme-row.tsx +++ b/app/src/components/settings/theme-row.tsx @@ -1,4 +1,4 @@ -import { IconSunMoon } from "@tabler/icons-react"; +import { IconSunMoon } from "@/components/icons"; import { useTheme } from "@/components/theme-provider"; import { Item, diff --git a/app/src/components/settings/this-computer-sections.tsx b/app/src/components/settings/this-computer-sections.tsx index 54912eccc9..d9bcd5152e 100644 --- a/app/src/components/settings/this-computer-sections.tsx +++ b/app/src/components/settings/this-computer-sections.tsx @@ -12,7 +12,7 @@ import { IconServer, IconSparkles, IconTerminal2, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import * as React from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; diff --git a/app/src/components/settings/update-routing.tsx b/app/src/components/settings/update-routing.tsx index f8348f9ffc..64371f45a3 100644 --- a/app/src/components/settings/update-routing.tsx +++ b/app/src/components/settings/update-routing.tsx @@ -1,4 +1,4 @@ -import { IconRoute } from "@tabler/icons-react"; +import { IconRoute } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment } from "react"; import { diff --git a/app/src/components/settings/usage-data.tsx b/app/src/components/settings/usage-data.tsx index 543a9eca70..acfa4f9bb0 100644 --- a/app/src/components/settings/usage-data.tsx +++ b/app/src/components/settings/usage-data.tsx @@ -1,4 +1,4 @@ -import { IconChartBar } from "@tabler/icons-react"; +import { IconChartBar } from "@/components/icons"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { diff --git a/app/src/components/settings/your-ai.tsx b/app/src/components/settings/your-ai.tsx index 0fec775040..bec9b6fa80 100644 --- a/app/src/components/settings/your-ai.tsx +++ b/app/src/components/settings/your-ai.tsx @@ -2,7 +2,7 @@ import { IconBuilding, IconChevronRight, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/components/setup/setup-checklist.tsx b/app/src/components/setup/setup-checklist.tsx index 2dcc190b3c..c1e126d990 100644 --- a/app/src/components/setup/setup-checklist.tsx +++ b/app/src/components/setup/setup-checklist.tsx @@ -4,7 +4,7 @@ import { IconDeviceDesktop, IconMessages, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Fragment } from "react"; import { PageRows } from "@/components/layout/page-shell"; diff --git a/app/src/components/skills/skill-tools.tsx b/app/src/components/skills/skill-tools.tsx index c7648d4d0f..f8bc7d32f4 100644 --- a/app/src/components/skills/skill-tools.tsx +++ b/app/src/components/skills/skill-tools.tsx @@ -1,5 +1,5 @@ import { RESEARCH_ROLES } from "@openbot/shared/research"; -import { IconChevronRight, IconPlugOff, IconWorld } from "@tabler/icons-react"; +import { IconChevronRight, IconPlugOff, IconWorld } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type ReactNode, useState } from "react"; import { PageRows } from "@/components/layout/page-shell"; diff --git a/app/src/components/skills/skills-settings-page.tsx b/app/src/components/skills/skills-settings-page.tsx index 067463f39b..f1db62552a 100644 --- a/app/src/components/skills/skills-settings-page.tsx +++ b/app/src/components/skills/skills-settings-page.tsx @@ -4,7 +4,7 @@ import { IconChevronRight, IconDots, IconPlus, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link, useNavigate } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/components/star-prompt/star-prompt.tsx b/app/src/components/star-prompt/star-prompt.tsx index 13f76cdd26..e99dd00521 100644 --- a/app/src/components/star-prompt/star-prompt.tsx +++ b/app/src/components/star-prompt/star-prompt.tsx @@ -1,5 +1,5 @@ import { STAR_ON_GITHUB } from "@openbot/shared/notices"; -import { IconStar } from "@tabler/icons-react"; +import { IconStar } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { Button, buttonVariants } from "@/components/ui/button"; diff --git a/app/src/components/suggestions/check-in-page.tsx b/app/src/components/suggestions/check-in-page.tsx index 04ba387784..b9b2d63294 100644 --- a/app/src/components/suggestions/check-in-page.tsx +++ b/app/src/components/suggestions/check-in-page.tsx @@ -3,7 +3,7 @@ import { IconPlayerPlay, IconRadar, IconRepeat, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { type LinkProps, useNavigate } from "@tanstack/react-router"; import { useId, useState } from "react"; diff --git a/app/src/components/suggestions/proactive-panel.tsx b/app/src/components/suggestions/proactive-panel.tsx index 95c90985e3..aa8e0de557 100644 --- a/app/src/components/suggestions/proactive-panel.tsx +++ b/app/src/components/suggestions/proactive-panel.tsx @@ -4,7 +4,7 @@ import { IconChevronRight, IconPlus, IconRadar, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment, useId, useState } from "react"; diff --git a/app/src/components/suggestions/suggestion-row.tsx b/app/src/components/suggestions/suggestion-row.tsx index 694cac86a9..7413142efa 100644 --- a/app/src/components/suggestions/suggestion-row.tsx +++ b/app/src/components/suggestions/suggestion-row.tsx @@ -3,7 +3,7 @@ import { IconDots, IconRadar, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { stashFirstMessage } from "@/components/channels/transcript-messages"; diff --git a/app/src/components/tasks/task-details.tsx b/app/src/components/tasks/task-details.tsx index 2f4cd50478..3ad70ae4d8 100644 --- a/app/src/components/tasks/task-details.tsx +++ b/app/src/components/tasks/task-details.tsx @@ -6,7 +6,7 @@ import { IconFileText, IconPlug, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type ReactNode, useState } from "react"; import { HarnessMark } from "@/components/agents/harness-mark"; diff --git a/app/src/components/tasks/task-row.tsx b/app/src/components/tasks/task-row.tsx index df79a79217..8966e61386 100644 --- a/app/src/components/tasks/task-row.tsx +++ b/app/src/components/tasks/task-row.tsx @@ -6,7 +6,7 @@ import { IconHandStop, IconPlayerStop, IconProgress, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import type { HeldAnswer } from "@/components/approvals/waiting"; diff --git a/app/src/components/tasks/task-steer.tsx b/app/src/components/tasks/task-steer.tsx index 25d71c1082..f7c65498ce 100644 --- a/app/src/components/tasks/task-steer.tsx +++ b/app/src/components/tasks/task-steer.tsx @@ -1,4 +1,4 @@ -import { IconCornerDownRight } from "@tabler/icons-react"; +import { IconCornerDownRight } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { useEffect } from "react"; import { relativeTimeShort } from "@/lib/relative-time"; diff --git a/app/src/components/tasks/task-thread.tsx b/app/src/components/tasks/task-thread.tsx index bd8e358e5d..f06503ba02 100644 --- a/app/src/components/tasks/task-thread.tsx +++ b/app/src/components/tasks/task-thread.tsx @@ -9,7 +9,7 @@ import { IconHandStop, IconPlayerStop, IconProgress, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { QueryClientContext, useMutation, diff --git a/app/src/components/team-grants/team-grants-row.tsx b/app/src/components/team-grants/team-grants-row.tsx index 1bba173dff..b7a5ff0e9c 100644 --- a/app/src/components/team-grants/team-grants-row.tsx +++ b/app/src/components/team-grants/team-grants-row.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, IconUsersGroup } from "@tabler/icons-react"; +import { IconChevronRight, IconUsersGroup } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/teams/new-team-page.tsx b/app/src/components/teams/new-team-page.tsx index 1d0510db33..c21129c046 100644 --- a/app/src/components/teams/new-team-page.tsx +++ b/app/src/components/teams/new-team-page.tsx @@ -1,4 +1,4 @@ -import { IconUsersGroup } from "@tabler/icons-react"; +import { IconUsersGroup } from "@/components/icons"; import { useForm } from "@tanstack/react-form"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link, useNavigate } from "@tanstack/react-router"; diff --git a/app/src/components/teams/people-typeahead.tsx b/app/src/components/teams/people-typeahead.tsx index e60a6b294c..60cf878dff 100644 --- a/app/src/components/teams/people-typeahead.tsx +++ b/app/src/components/teams/people-typeahead.tsx @@ -1,4 +1,4 @@ -import { IconCornerDownLeft, IconSearch } from "@tabler/icons-react"; +import { IconCornerDownLeft, IconSearch } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { type KeyboardEvent, diff --git a/app/src/components/teams/team-models.tsx b/app/src/components/teams/team-models.tsx index 7875ce1942..5c0f14535e 100644 --- a/app/src/components/teams/team-models.tsx +++ b/app/src/components/teams/team-models.tsx @@ -3,7 +3,7 @@ import { IconChevronRight, IconCube, IconSearch, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { allowlistNarrows } from "@/components/admin/controls/model-sections"; diff --git a/app/src/components/teams/team-page.tsx b/app/src/components/teams/team-page.tsx index 85545aae14..0d0981dff7 100644 --- a/app/src/components/teams/team-page.tsx +++ b/app/src/components/teams/team-page.tsx @@ -9,7 +9,7 @@ import { IconSitemap, IconUser, IconUsers, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { keepPreviousData, useInfiniteQuery, diff --git a/app/src/components/teams/teams-page.tsx b/app/src/components/teams/teams-page.tsx index 4597962707..805e32f52a 100644 --- a/app/src/components/teams/teams-page.tsx +++ b/app/src/components/teams/teams-page.tsx @@ -4,7 +4,7 @@ import { IconPlus, IconSearch, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { useEffect, useState } from "react"; diff --git a/app/src/components/ui/carousel.tsx b/app/src/components/ui/carousel.tsx index c509b86f45..52af53fe51 100644 --- a/app/src/components/ui/carousel.tsx +++ b/app/src/components/ui/carousel.tsx @@ -1,4 +1,4 @@ -import { IconChevronLeft, IconChevronRight } from "@tabler/icons-react"; +import { IconChevronLeft, IconChevronRight } from "@/components/icons"; import useEmblaCarousel, { type UseEmblaCarouselType, } from "embla-carousel-react"; diff --git a/app/src/components/ui/checkbox.tsx b/app/src/components/ui/checkbox.tsx index 7c7ab66388..699acdf8a7 100644 --- a/app/src/components/ui/checkbox.tsx +++ b/app/src/components/ui/checkbox.tsx @@ -1,5 +1,5 @@ import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"; -import { IconCheck } from "@tabler/icons-react"; +import { IconCheck } from "@/components/icons"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/combobox.tsx b/app/src/components/ui/combobox.tsx index 13a2242fdd..ccc5fedc17 100644 --- a/app/src/components/ui/combobox.tsx +++ b/app/src/components/ui/combobox.tsx @@ -1,7 +1,7 @@ "use client"; import { Combobox as ComboboxPrimitive } from "@base-ui/react"; -import { IconCheck, IconChevronDown, IconX } from "@tabler/icons-react"; +import { IconCheck, IconChevronDown, IconX } from "@/components/icons"; import * as React from "react"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/ui/context-menu.tsx b/app/src/components/ui/context-menu.tsx index d2c30ae94f..e4070df8e5 100644 --- a/app/src/components/ui/context-menu.tsx +++ b/app/src/components/ui/context-menu.tsx @@ -1,5 +1,5 @@ import { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"; -import { IconCheck, IconChevronRight } from "@tabler/icons-react"; +import { IconCheck, IconChevronRight } from "@/components/icons"; import type * as React from "react"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/dialog.tsx b/app/src/components/ui/dialog.tsx index ac89fd1780..23ac86d511 100644 --- a/app/src/components/ui/dialog.tsx +++ b/app/src/components/ui/dialog.tsx @@ -1,5 +1,5 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; -import { IconX } from "@tabler/icons-react"; +import { IconX } from "@/components/icons"; import type * as React from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/ui/dropdown-menu.tsx b/app/src/components/ui/dropdown-menu.tsx index d608f01bbc..1d10df9abc 100644 --- a/app/src/components/ui/dropdown-menu.tsx +++ b/app/src/components/ui/dropdown-menu.tsx @@ -1,5 +1,5 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu"; -import { IconCheck, IconChevronRight } from "@tabler/icons-react"; +import { IconCheck, IconChevronRight } from "@/components/icons"; import type * as React from "react"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/message-scroller.tsx b/app/src/components/ui/message-scroller.tsx index e22fdeb30c..a5f753b914 100644 --- a/app/src/components/ui/message-scroller.tsx +++ b/app/src/components/ui/message-scroller.tsx @@ -4,7 +4,7 @@ import { useMessageScrollerScrollable, useMessageScrollerVisibility, } from "@shadcn/react/message-scroller"; -import { IconArrowDown } from "@tabler/icons-react"; +import { IconArrowDown } from "@/components/icons"; import type * as React from "react"; import { useCallback, useRef } from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/ui/questionnaire.tsx b/app/src/components/ui/questionnaire.tsx index 4c997184c2..d184babc09 100644 --- a/app/src/components/ui/questionnaire.tsx +++ b/app/src/components/ui/questionnaire.tsx @@ -1,5 +1,5 @@ import { Questionnaire as QuestionnairePrimitive } from "@shadcn/react/questionnaire"; -import { IconCheck } from "@tabler/icons-react"; +import { IconCheck } from "@/components/icons"; import type * as React from "react"; import { type Button, buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/select.tsx b/app/src/components/ui/select.tsx index 7d9fe6b2f0..597cb5bf8d 100644 --- a/app/src/components/ui/select.tsx +++ b/app/src/components/ui/select.tsx @@ -4,7 +4,7 @@ import { IconChevronDown, IconChevronUp, IconSelector, -} from "@tabler/icons-react"; +} from "@/components/icons"; import type * as React from "react"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/sheet.tsx b/app/src/components/ui/sheet.tsx index 8d8119a6d7..edf00a0f8b 100644 --- a/app/src/components/ui/sheet.tsx +++ b/app/src/components/ui/sheet.tsx @@ -1,5 +1,5 @@ import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"; -import { IconX } from "@tabler/icons-react"; +import { IconX } from "@/components/icons"; import type * as React from "react"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; diff --git a/app/src/components/ui/sidebar.tsx b/app/src/components/ui/sidebar.tsx index 92842e5bf0..5748861fbc 100644 --- a/app/src/components/ui/sidebar.tsx +++ b/app/src/components/ui/sidebar.tsx @@ -2,7 +2,7 @@ import { mergeProps } from "@base-ui/react/merge-props"; import { useRender } from "@base-ui/react/use-render"; -import { IconLayoutSidebar } from "@tabler/icons-react"; +import { IconLayoutSidebar } from "@/components/icons"; import { cva, type VariantProps } from "class-variance-authority"; import * as React from "react"; import * as ReactDOM from "react-dom"; diff --git a/app/src/components/ui/toast.tsx b/app/src/components/ui/toast.tsx index 5322d9373f..26a3c7a270 100644 --- a/app/src/components/ui/toast.tsx +++ b/app/src/components/ui/toast.tsx @@ -11,7 +11,7 @@ import { IconInfoCircle, IconLoader, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import type * as React from "react"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/vault/saved-logins.tsx b/app/src/components/vault/saved-logins.tsx index 4effe5d255..6a5f2b8d00 100644 --- a/app/src/components/vault/saved-logins.tsx +++ b/app/src/components/vault/saved-logins.tsx @@ -3,7 +3,7 @@ import { IconKey, IconLockOff, IconTrash, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { PageEmpty, PageRows } from "@/components/layout/page-shell"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/vault/vault-page.tsx b/app/src/components/vault/vault-page.tsx index 8dd9a5864a..7a6f5f1f7d 100644 --- a/app/src/components/vault/vault-page.tsx +++ b/app/src/components/vault/vault-page.tsx @@ -1,4 +1,4 @@ -import { IconPlus } from "@tabler/icons-react"; +import { IconPlus } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { PageSection, PageShell } from "@/components/layout/page-shell"; import { CredentialsList } from "@/components/manage/credentials-page"; diff --git a/app/src/components/what-if/action-chips.tsx b/app/src/components/what-if/action-chips.tsx index 9036f47e1e..c36912c3b3 100644 --- a/app/src/components/what-if/action-chips.tsx +++ b/app/src/components/what-if/action-chips.tsx @@ -12,7 +12,7 @@ import { whatIfTeamGroup, whatIfTeamOf, } from "@openbot/shared/what-if"; -import { IconChevronDown } from "@tabler/icons-react"; +import { IconChevronDown } from "@/components/icons"; import { type ReactNode, useId, useState } from "react"; import { Button } from "@/components/ui/button"; import { diff --git a/app/src/components/what-if/what-if-result.tsx b/app/src/components/what-if/what-if-result.tsx index 3f39ca194c..cae3a80453 100644 --- a/app/src/components/what-if/what-if-result.tsx +++ b/app/src/components/what-if/what-if-result.tsx @@ -18,7 +18,7 @@ import { IconPuzzle, IconShieldCheck, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { Link } from "@tanstack/react-router"; import type * as React from "react"; import { PageRows } from "@/components/layout/page-shell"; diff --git a/app/src/components/what-if/why-button.tsx b/app/src/components/what-if/why-button.tsx index 6580348940..c4f84574e1 100644 --- a/app/src/components/what-if/why-button.tsx +++ b/app/src/components/what-if/why-button.tsx @@ -1,5 +1,5 @@ import { whatIfExplainable } from "@openbot/shared/what-if"; -import { IconHelpCircle } from "@tabler/icons-react"; +import { IconHelpCircle } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { useState } from "react"; import type { AuditEvent } from "@/components/audit/audit-cells"; diff --git a/app/src/components/windows-computer/connect-windows-computer.tsx b/app/src/components/windows-computer/connect-windows-computer.tsx index 773e1cd12c..6c75b234fb 100644 --- a/app/src/components/windows-computer/connect-windows-computer.tsx +++ b/app/src/components/windows-computer/connect-windows-computer.tsx @@ -1,6 +1,6 @@ -import { IconDeviceDesktop, IconPlugConnected } from "@tabler/icons-react"; import { useMutation } from "@tanstack/react-query"; import { useState } from "react"; +import { IconDeviceDesktop, IconPlugConnected } from "@/components/icons"; import { PageEmpty } from "@/components/layout/page-shell"; import { copyText } from "@/components/settings/linked-accounts"; import { Button } from "@/components/ui/button"; diff --git a/app/src/components/windows-computer/windows-computer-choice.tsx b/app/src/components/windows-computer/windows-computer-choice.tsx index 2eac2b9601..5bafce3fb2 100644 --- a/app/src/components/windows-computer/windows-computer-choice.tsx +++ b/app/src/components/windows-computer/windows-computer-choice.tsx @@ -1,6 +1,6 @@ -import { IconBrandWindows } from "@tabler/icons-react"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; +import { IconBrandWindows } from "@/components/icons"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { Item, diff --git a/app/src/components/windows-computer/windows-computer-page.tsx b/app/src/components/windows-computer/windows-computer-page.tsx index 3584a5b7ad..dbc4b00fcf 100644 --- a/app/src/components/windows-computer/windows-computer-page.tsx +++ b/app/src/components/windows-computer/windows-computer-page.tsx @@ -1,4 +1,7 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { type ReactNode, useRef, useState } from "react"; +import { LiveScreen } from "@/components/computer/live-screen"; import { IconDeviceDesktop, IconPlayerRecord, @@ -6,10 +9,7 @@ import { IconPointer, IconRobot, IconX, -} from "@tabler/icons-react"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { type ReactNode, useRef, useState } from "react"; -import { LiveScreen } from "@/components/computer/live-screen"; +} from "@/components/icons"; import { PageEmpty, PageRows, diff --git a/app/src/lib/copilot/check-in-offer-tool.tsx b/app/src/lib/copilot/check-in-offer-tool.tsx index 5402787d9f..3629f3c43a 100644 --- a/app/src/lib/copilot/check-in-offer-tool.tsx +++ b/app/src/lib/copilot/check-in-offer-tool.tsx @@ -1,6 +1,6 @@ import { useRenderTool } from "@copilotkit/react-core/v2"; import { OFFER_CHECK_IN_TOOL } from "@openbot/shared/check-in-offer"; -import { IconRadar } from "@tabler/icons-react"; +import { IconRadar } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useParams } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/lib/copilot/sign-in-tool.tsx b/app/src/lib/copilot/sign-in-tool.tsx index 9e00b884f5..9b03663191 100644 --- a/app/src/lib/copilot/sign-in-tool.tsx +++ b/app/src/lib/copilot/sign-in-tool.tsx @@ -1,4 +1,4 @@ -import { IconLock } from "@tabler/icons-react"; +import { IconLock } from "@/components/icons"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useState } from "react"; import { z } from "zod"; diff --git a/app/src/lib/markdown.tsx b/app/src/lib/markdown.tsx index bb035d2007..9c82f936d5 100644 --- a/app/src/lib/markdown.tsx +++ b/app/src/lib/markdown.tsx @@ -3,7 +3,7 @@ import { IconFileText, IconPresentation, IconTable, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useRouter } from "@tanstack/react-router"; import { type ComponentProps, diff --git a/app/src/lib/navigation.ts b/app/src/lib/navigation.ts index b0e621e4b4..882e7d9bd7 100644 --- a/app/src/lib/navigation.ts +++ b/app/src/lib/navigation.ts @@ -5,7 +5,7 @@ import { IconSettings, IconShieldLock, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { OpenBotLogo } from "@/components/edition/openbot-logo"; import { currentUserQueryOptions } from "@/lib/auth/queries"; diff --git a/app/src/lib/primitives.ts b/app/src/lib/primitives.ts index 5502786343..bd7db0f089 100644 --- a/app/src/lib/primitives.ts +++ b/app/src/lib/primitives.ts @@ -10,7 +10,7 @@ import { IconMessages, IconPlug, IconSettings, -} from "@tabler/icons-react"; +} from "@/components/icons"; /** * The eight things a Bot has, in the one order every list of them keeps: on a Bot's page, in diff --git a/app/src/routes/_authed/_app/bot.tsx b/app/src/routes/_authed/_app/bot.tsx index bb1ed2b62f..6ebaa479da 100644 --- a/app/src/routes/_authed/_app/bot.tsx +++ b/app/src/routes/_authed/_app/bot.tsx @@ -1,5 +1,5 @@ import { CopilotChat } from "@copilotkit/react-core/v2"; -import { IconPlus } from "@tabler/icons-react"; +import { IconPlus } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/routes/_authed/_app/bots.index.tsx b/app/src/routes/_authed/_app/bots.index.tsx index 0963cfcec3..ebf3f47dbb 100644 --- a/app/src/routes/_authed/_app/bots.index.tsx +++ b/app/src/routes/_authed/_app/bots.index.tsx @@ -3,7 +3,7 @@ import { IconBrain, IconChevronRight, IconPlus, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { z } from "zod"; diff --git a/app/src/routes/_authed/_app/channel/$channelId.tsx b/app/src/routes/_authed/_app/channel/$channelId.tsx index 596f3c875c..6e61ad5961 100644 --- a/app/src/routes/_authed/_app/channel/$channelId.tsx +++ b/app/src/routes/_authed/_app/channel/$channelId.tsx @@ -1,4 +1,4 @@ -import { IconListDetails, IconSettings } from "@tabler/icons-react"; +import { IconListDetails, IconSettings } from "@/components/icons"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { createFileRoute, Navigate } from "@tanstack/react-router"; import { motion, useReducedMotion } from "motion/react"; diff --git a/app/src/routes/_authed/_app/connections.$key.tsx b/app/src/routes/_authed/_app/connections.$key.tsx index 5ca5ee8c0d..06ad95f604 100644 --- a/app/src/routes/_authed/_app/connections.$key.tsx +++ b/app/src/routes/_authed/_app/connections.$key.tsx @@ -1,3 +1,7 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { createFileRoute, useParams } from "@tanstack/react-router"; +import { useEffect, useRef, useState } from "react"; +import { IdentityConnectionPage } from "@/components/connections/identity-connection-page"; import { IconAppsOff, IconArrowUpRight, @@ -5,11 +9,7 @@ import { IconPlug, IconPlugOff, IconUsers, -} from "@tabler/icons-react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { createFileRoute, useParams } from "@tanstack/react-router"; -import { useEffect, useRef, useState } from "react"; -import { IdentityConnectionPage } from "@/components/connections/identity-connection-page"; +} from "@/components/icons"; import { PageEmpty, PageRows, diff --git a/app/src/routes/_authed/_app/connections.index.tsx b/app/src/routes/_authed/_app/connections.index.tsx index 0fe4ad78f0..aa0c4327d5 100644 --- a/app/src/routes/_authed/_app/connections.index.tsx +++ b/app/src/routes/_authed/_app/connections.index.tsx @@ -8,7 +8,7 @@ import { IconPlug, IconPlus, IconSearch, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute, diff --git a/app/src/routes/_authed/_app/reconnect.tsx b/app/src/routes/_authed/_app/reconnect.tsx index 95b1d1495b..cea8ceb1a4 100644 --- a/app/src/routes/_authed/_app/reconnect.tsx +++ b/app/src/routes/_authed/_app/reconnect.tsx @@ -1,4 +1,4 @@ -import { IconCheck, IconX } from "@tabler/icons-react"; +import { IconCheck, IconX } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute, Link, useNavigate } from "@tanstack/react-router"; import * as React from "react"; diff --git a/app/src/routes/_authed/admin/approvals_.guidance.tsx b/app/src/routes/_authed/admin/approvals_.guidance.tsx index 5d0927b3de..32b66834fd 100644 --- a/app/src/routes/_authed/admin/approvals_.guidance.tsx +++ b/app/src/routes/_authed/admin/approvals_.guidance.tsx @@ -1,4 +1,4 @@ -import { IconShieldLock } from "@tabler/icons-react"; +import { IconShieldLock } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/routes/_authed/admin/boundaries.tsx b/app/src/routes/_authed/admin/boundaries.tsx index 7bff9e8d13..71baf60116 100644 --- a/app/src/routes/_authed/admin/boundaries.tsx +++ b/app/src/routes/_authed/admin/boundaries.tsx @@ -3,7 +3,7 @@ import { IconListSearch, IconPlus, IconShieldX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { diff --git a/app/src/routes/_authed/admin/boundaries_.new.tsx b/app/src/routes/_authed/admin/boundaries_.new.tsx index fb73893439..bb2b01b486 100644 --- a/app/src/routes/_authed/admin/boundaries_.new.tsx +++ b/app/src/routes/_authed/admin/boundaries_.new.tsx @@ -3,7 +3,7 @@ import { IconCode, IconShieldX, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { keepPreviousData, useMutation, diff --git a/app/src/routes/_authed/admin/components/$name.tsx b/app/src/routes/_authed/admin/components/$name.tsx index f0d49ba350..024d018eef 100644 --- a/app/src/routes/_authed/admin/components/$name.tsx +++ b/app/src/routes/_authed/admin/components/$name.tsx @@ -8,7 +8,7 @@ import { IconTag, IconUsers, IconWorld, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { type ReactNode, useState } from "react"; diff --git a/app/src/routes/_authed/admin/identity-providers.tsx b/app/src/routes/_authed/admin/identity-providers.tsx index 6558da090b..4e3764b43e 100644 --- a/app/src/routes/_authed/admin/identity-providers.tsx +++ b/app/src/routes/_authed/admin/identity-providers.tsx @@ -1,4 +1,4 @@ -import { IconBuildingBank, IconTrash } from "@tabler/icons-react"; +import { IconBuildingBank, IconTrash } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute, redirect } from "@tanstack/react-router"; import { useId, useState } from "react"; diff --git a/app/src/routes/_authed/admin/index.tsx b/app/src/routes/_authed/admin/index.tsx index 7833aae26a..8ca5c58dfd 100644 --- a/app/src/routes/_authed/admin/index.tsx +++ b/app/src/routes/_authed/admin/index.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight } from "@tabler/icons-react"; +import { IconChevronRight } from "@/components/icons"; import { createFileRoute, Link } from "@tanstack/react-router"; import { useAdminSections } from "@/components/admin/admin-sections"; import { SharedComputersNotice } from "@/components/admin/shared-computers-notice"; diff --git a/app/src/routes/_authed/admin/learning.tsx b/app/src/routes/_authed/admin/learning.tsx index 2aca0ca1db..da6f4d19c9 100644 --- a/app/src/routes/_authed/admin/learning.tsx +++ b/app/src/routes/_authed/admin/learning.tsx @@ -6,7 +6,7 @@ import { IconChevronRight, IconHistory, IconSparkles, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { Fragment, useId, useState } from "react"; diff --git a/app/src/routes/_authed/admin/management.tsx b/app/src/routes/_authed/admin/management.tsx index 9258f08b40..92fd17a789 100644 --- a/app/src/routes/_authed/admin/management.tsx +++ b/app/src/routes/_authed/admin/management.tsx @@ -11,7 +11,7 @@ import { IconLock, IconTag, IconTool, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/routes/_authed/admin/people.tsx b/app/src/routes/_authed/admin/people.tsx index 9af0a9742d..4867a478ee 100644 --- a/app/src/routes/_authed/admin/people.tsx +++ b/app/src/routes/_authed/admin/people.tsx @@ -4,7 +4,7 @@ import { IconShieldCheck, IconUser, IconUsers, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { useEffect, useState } from "react"; diff --git a/app/src/routes/_authed/admin/proactive.tsx b/app/src/routes/_authed/admin/proactive.tsx index f1450662c7..6966814034 100644 --- a/app/src/routes/_authed/admin/proactive.tsx +++ b/app/src/routes/_authed/admin/proactive.tsx @@ -3,7 +3,7 @@ import { IconChevronRight, IconGauge, IconRadar, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { keepPreviousData, type UseQueryResult, diff --git a/app/src/routes/_authed/admin/what-if.tsx b/app/src/routes/_authed/admin/what-if.tsx index 4a08a7dd2e..1f7a95e291 100644 --- a/app/src/routes/_authed/admin/what-if.tsx +++ b/app/src/routes/_authed/admin/what-if.tsx @@ -3,7 +3,7 @@ import { missingFrom, type WhatIfAction, } from "@openbot/shared/what-if"; -import { IconSparkles } from "@tabler/icons-react"; +import { IconSparkles } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; diff --git a/app/src/routes/_authed/settings/components-gallery/$name.tsx b/app/src/routes/_authed/settings/components-gallery/$name.tsx index c6299d5ad3..d91c555ff2 100644 --- a/app/src/routes/_authed/settings/components-gallery/$name.tsx +++ b/app/src/routes/_authed/settings/components-gallery/$name.tsx @@ -1,4 +1,4 @@ -import { IconCode, IconTag } from "@tabler/icons-react"; +import { IconCode, IconTag } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import type { ReactNode } from "react"; diff --git a/app/src/skins/opendots/computer-pane.tsx b/app/src/skins/opendots/computer-pane.tsx index 4be6544086..9f31e60edb 100644 --- a/app/src/skins/opendots/computer-pane.tsx +++ b/app/src/skins/opendots/computer-pane.tsx @@ -1,4 +1,4 @@ -import { IconDeviceDesktop, IconX } from "@tabler/icons-react"; +import { IconDeviceDesktop, IconX } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { ComputerViewPanel } from "@/components/computer/computer-panel"; diff --git a/app/src/skins/opendots/frame.tsx b/app/src/skins/opendots/frame.tsx index 4389f7523d..ee45af5707 100644 --- a/app/src/skins/opendots/frame.tsx +++ b/app/src/skins/opendots/frame.tsx @@ -8,7 +8,7 @@ import { IconPlayerPlay, IconPlus, IconSearch, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link, diff --git a/app/src/skins/opendots/persona.tsx b/app/src/skins/opendots/persona.tsx index e06f46de67..b2107d8411 100644 --- a/app/src/skins/opendots/persona.tsx +++ b/app/src/skins/opendots/persona.tsx @@ -1,4 +1,4 @@ -import { IconDots } from "@tabler/icons-react"; +import { IconDots } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { AbstractAvatar } from "@/components/agents/abstract-avatar"; diff --git a/app/src/skins/opendots/sidebar.tsx b/app/src/skins/opendots/sidebar.tsx index f826321c81..bca3f2abe9 100644 --- a/app/src/skins/opendots/sidebar.tsx +++ b/app/src/skins/opendots/sidebar.tsx @@ -10,7 +10,7 @@ import { IconSearch, IconTrash, IconX, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { Link, type LinkProps, useNavigate } from "@tanstack/react-router"; import { type ReactNode, useRef, useState } from "react"; diff --git a/app/src/skins/openduet/header.tsx b/app/src/skins/openduet/header.tsx index 232490c8e0..d31547c6cf 100644 --- a/app/src/skins/openduet/header.tsx +++ b/app/src/skins/openduet/header.tsx @@ -1,4 +1,4 @@ -import { IconChevronLeft } from "@tabler/icons-react"; +import { IconChevronLeft } from "@/components/icons"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link, diff --git a/app/src/skins/openduet/icons.ts b/app/src/skins/openduet/icons.ts index afa80cacec..6df3034706 100644 --- a/app/src/skins/openduet/icons.ts +++ b/app/src/skins/openduet/icons.ts @@ -1,41 +1,35 @@ -import { createReactComponent } from "@tabler/icons-react"; +import { defineIcon, GLYPH_STROKE } from "@/components/icons"; /* - * Two of OpenDuet's glyphs have no Tabler twin, and they are the two a person sees on every screen: - * the menu (two long lines over a short one) and the Tasks tab (a box, a check, three lines). They - * are made as Tabler icons, on Tabler's 24-unit grid with its round caps and props, so they sit in - * a row of Tabler icons at the same weight. Everything else in the skin is Tabler's own. + * Two of OpenDuet's glyphs have no twin in the icon set, and they are the two a person sees on every + * screen: the menu (two long lines over a short one) and the Tasks tab (a box, a check, three lines). + * They are drawn on the set's 24-unit grid with its round caps and line, so they sit in a row of the + * set's icons at the same weight. Everything else in the skin is the set's own. */ -export const IconMenuShort = createReactComponent( - "outline", - "menu-short", - "MenuShort", - [["path", { d: "M4 7h16M4 12h16M4 17h10", key: "menu-short-lines" }]], -); +export const IconMenuShort = defineIcon("menu-short", [ + ["path", { d: "M4 7h16M4 12h16M4 17h10", key: "lines", ...GLYPH_STROKE }], +]); -export const IconTasksList = createReactComponent( - "outline", - "tasks-list", - "TasksList", +export const IconTasksList = defineIcon("tasks-list", [ [ - [ - "rect", - { - x: "3", - y: "4", - width: "6", - height: "6", - rx: "1.5", - key: "tasks-list-box", - }, - ], - [ - "path", - { - d: "m3 17 2 2 4-4M13 5h8M13 12h8M13 19h8", - key: "tasks-list-lines", - }, - ], + "rect", + { + x: "3", + y: "4", + width: "6", + height: "6", + rx: "1.5", + key: "box", + ...GLYPH_STROKE, + }, ], -); + [ + "path", + { + d: "m3 17 2 2 4-4M13 5h8M13 12h8M13 19h8", + key: "lines", + ...GLYPH_STROKE, + }, + ], +]); diff --git a/app/src/skins/openduet/menu-sheet.tsx b/app/src/skins/openduet/menu-sheet.tsx index 332288daba..4cd0a72688 100644 --- a/app/src/skins/openduet/menu-sheet.tsx +++ b/app/src/skins/openduet/menu-sheet.tsx @@ -8,7 +8,7 @@ import { IconSearch, IconStack2, IconTrash, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { Link, useNavigate, useParams } from "@tanstack/react-router"; import { type ReactNode, useId, useRef, useState } from "react"; diff --git a/app/src/skins/openduet/tab-bar.tsx b/app/src/skins/openduet/tab-bar.tsx index e7bcc8e35a..f2d51c0d47 100644 --- a/app/src/skins/openduet/tab-bar.tsx +++ b/app/src/skins/openduet/tab-bar.tsx @@ -1,4 +1,4 @@ -import { IconMessageCircle } from "@tabler/icons-react"; +import { IconMessageCircle } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { useWaitingCount } from "@/components/bot-profile/attention"; import { cn } from "@/lib/utils"; diff --git a/app/src/skins/openfuse/bots-sheet.tsx b/app/src/skins/openfuse/bots-sheet.tsx index 55250b7713..3b7dbbc525 100644 --- a/app/src/skins/openfuse/bots-sheet.tsx +++ b/app/src/skins/openfuse/bots-sheet.tsx @@ -3,7 +3,7 @@ import { IconCheck, IconPlus, IconUserCircle, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link, useNavigate, useRouterState } from "@tanstack/react-router"; import { AbstractAvatar } from "@/components/agents/abstract-avatar"; diff --git a/app/src/skins/openfuse/frame.tsx b/app/src/skins/openfuse/frame.tsx index 1ab26b6328..cb5d83fac0 100644 --- a/app/src/skins/openfuse/frame.tsx +++ b/app/src/skins/openfuse/frame.tsx @@ -7,7 +7,7 @@ import { IconSquareCheck, IconTable, IconTriangleSquareCircle, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link, useParams, useRouterState } from "@tanstack/react-router"; import { type ReactNode, useEffect, useState } from "react"; diff --git a/app/src/skins/openfuse/menu-sheet.tsx b/app/src/skins/openfuse/menu-sheet.tsx index cf6735270c..04d2b94fa8 100644 --- a/app/src/skins/openfuse/menu-sheet.tsx +++ b/app/src/skins/openfuse/menu-sheet.tsx @@ -9,7 +9,7 @@ import { IconSearch, IconTrash, IconUsersGroup, -} from "@tabler/icons-react"; +} from "@/components/icons"; import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; import { Link, useNavigate, useParams } from "@tanstack/react-router"; import { useRef, useState } from "react"; diff --git a/app/src/skins/openfuse/notifications-sheet.tsx b/app/src/skins/openfuse/notifications-sheet.tsx index a57ad3ddf1..7929e3bf75 100644 --- a/app/src/skins/openfuse/notifications-sheet.tsx +++ b/app/src/skins/openfuse/notifications-sheet.tsx @@ -1,4 +1,4 @@ -import { IconBell, IconHandStop } from "@tabler/icons-react"; +import { IconBell, IconHandStop } from "@/components/icons"; import { Link } from "@tanstack/react-router"; import { useHeldAnswers, WaitingForYou } from "@/components/approvals/waiting"; import { ActivityRow } from "@/components/bot-profile/activity"; diff --git a/app/src/skins/openfuse/screens/activity.tsx b/app/src/skins/openfuse/screens/activity.tsx index 6469d6fca4..ebb576179c 100644 --- a/app/src/skins/openfuse/screens/activity.tsx +++ b/app/src/skins/openfuse/screens/activity.tsx @@ -1,4 +1,4 @@ -import { IconListCheck } from "@tabler/icons-react"; +import { IconListCheck } from "@/components/icons"; import { BotActivitySections } from "@/components/bot-profile/activity"; import { BotNeedsYou } from "@/components/needs-you/board"; import { isHeld, loadFailureText } from "@/lib/load-failure"; diff --git a/app/src/skins/openfuse/screens/ideas.tsx b/app/src/skins/openfuse/screens/ideas.tsx index 3b45a1a187..9c7740deca 100644 --- a/app/src/skins/openfuse/screens/ideas.tsx +++ b/app/src/skins/openfuse/screens/ideas.tsx @@ -1,4 +1,4 @@ -import { IconBulb } from "@tabler/icons-react"; +import { IconBulb } from "@/components/icons"; import { useQuery } from "@tanstack/react-query"; import { ProactiveResearchSettings, diff --git a/app/src/skins/openfuse/ui.tsx b/app/src/skins/openfuse/ui.tsx index 403ce8ab4d..283ad9aa13 100644 --- a/app/src/skins/openfuse/ui.tsx +++ b/app/src/skins/openfuse/ui.tsx @@ -1,4 +1,4 @@ -import { IconChevronRight, type IconProps, IconX } from "@tabler/icons-react"; +import { IconChevronRight, type IconProps, IconX } from "@/components/icons"; import * as React from "react"; import { BrandName } from "@/components/edition/brand-name"; import { Button, buttonVariants } from "@/components/ui/button"; diff --git a/app/src/skins/skin-picker.tsx b/app/src/skins/skin-picker.tsx index d2410b9266..3f3f13542c 100644 --- a/app/src/skins/skin-picker.tsx +++ b/app/src/skins/skin-picker.tsx @@ -1,4 +1,4 @@ -import { IconPalette } from "@tabler/icons-react"; +import { IconPalette } from "@/components/icons"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Item, diff --git a/app/src/theme.css b/app/src/theme.css index eac4bc61d1..49c0f9de66 100644 --- a/app/src/theme.css +++ b/app/src/theme.css @@ -202,15 +202,6 @@ body { @apply font-sans; } - /* - * Tabler draws every outline icon with a `stroke-width="2"` attribute unless it is given a - * `stroke`, and a CSS property outranks an SVG attribute. So this lightens the default line only; - * an icon given its own `stroke` keeps it (docs/app-guidelines.md, "The look"). - */ - .tabler-icon[stroke-width="2"] { - stroke-width: 1.75; - } - ::-webkit-scrollbar { width: 5px; } diff --git a/app/tests/admin-skills-pages.test.tsx b/app/tests/admin-skills-pages.test.tsx index 77ab3d0593..fc06751d96 100644 --- a/app/tests/admin-skills-pages.test.tsx +++ b/app/tests/admin-skills-pages.test.tsx @@ -195,7 +195,7 @@ describe("the Skills list", () => { ).toBeTruthy(); // The command is the skill's key, not something to read, and the row has no icon. expect(row?.textContent).not.toContain("/triage"); - expect(row?.querySelector("svg.tabler-icon-file-text")).toBeNull(); + expect(row?.querySelector("svg.icon-file-text")).toBeNull(); expect(within(row as HTMLElement).getByText("1 of 2 Bots")).toBeTruthy(); // No chip per Bot and no Remove on the row: those are on the skill's page. expect(view.queryByRole("button", { name: "Ada" })).toBeNull(); diff --git a/app/tests/bot-activity-groups.test.tsx b/app/tests/bot-activity-groups.test.tsx index 1384258f4f..46f80e0ae2 100644 --- a/app/tests/bot-activity-groups.test.tsx +++ b/app/tests/bot-activity-groups.test.tsx @@ -313,16 +313,12 @@ test("a task the person stopped reads Stopped on its row, in its card's words, a const row = (title: string) => view.getByText(title).closest("[data-slot=item]") as HTMLElement; expect(row("Task stopped").dataset.taskState).toBe("stopped"); - expect( - row("Task stopped").querySelector(".tabler-icon-player-stop"), - ).not.toBeNull(); - expect( - row("Task stopped").querySelector(".tabler-icon-alert-triangle"), - ).toBeNull(); + expect(row("Task stopped").querySelector(".icon-player-stop")).not.toBeNull(); + expect(row("Task stopped").querySelector(".icon-alert-triangle")).toBeNull(); expect(row("Task stopped").querySelector(".bg-destructive")).toBeNull(); expect(row("Task failed").dataset.taskState).toBe("failed"); expect( - row("Task failed").querySelector(".tabler-icon-alert-triangle"), + row("Task failed").querySelector(".icon-alert-triangle"), ).not.toBeNull(); // One that couldn't finish on its own still says so. diff --git a/app/tests/bot-manage.test.tsx b/app/tests/bot-manage.test.tsx index d82678efc9..2f8a6e0bcf 100644 --- a/app/tests/bot-manage.test.tsx +++ b/app/tests/bot-manage.test.tsx @@ -195,9 +195,7 @@ test("a Bot an admin assigned to you reads as pinned and cannot be hidden or unp test("rows that open a dialog show a chevron, and Duplicate, which acts at once, does not", () => { const view = draw(BOT); const chevron = (name: RegExp) => - view - .getByRole("button", { name }) - .querySelector(".tabler-icon-chevron-right"); + view.getByRole("button", { name }).querySelector(".icon-chevron-right"); expect(chevron(/^Reset/)).not.toBeNull(); expect(chevron(/^Delete/)).not.toBeNull(); expect(chevron(/^Duplicate/)).toBeNull(); diff --git a/app/tests/bot-profile-notice.test.tsx b/app/tests/bot-profile-notice.test.tsx index 79ae082deb..bb677d4e00 100644 --- a/app/tests/bot-profile-notice.test.tsx +++ b/app/tests/bot-profile-notice.test.tsx @@ -121,5 +121,5 @@ test("the Message row shows the chevron every row that goes somewhere carries", serving(); const view = draw(BOT); const row = (await view.findByText("Message Expenses")).closest("a"); - expect(row?.querySelector(".tabler-icon-chevron-right")).not.toBeNull(); + expect(row?.querySelector(".icon-chevron-right")).not.toBeNull(); }); diff --git a/app/tests/icon-set.test.ts b/app/tests/icon-set.test.ts new file mode 100644 index 0000000000..cfb21e0693 --- /dev/null +++ b/app/tests/icon-set.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative } from "node:path"; + +/* + * One icon set in every app (docs/design-system.md, "The rest of the look"): Hugeicons' free set, + * in the web app, the extension and OpenBot Desktop. A screen takes its icons from + * app/src/components/icons (Desktop, a package of its own, from desktop/src/icons.tsx; Desktop's + * workbench, which draws with the app's components, from the app's) and never names the set, so changing a glyph or the set is a change to those two files. A second set + * imported beside it, or the set imported around them, is how two looks of icon come back. + */ + +const ROOT = new URL("../../", import.meta.url).pathname; +const APP_ICONS = "app/src/components/icons/index.tsx"; +const DESKTOP_ICONS = "desktop/src/icons.tsx"; + +/** Every .ts and .tsx file under the repository's `dir`, relative to the repository. */ +function sourceFiles(dir: string): string[] { + const walk = (path: string): string[] => + statSync(path).isDirectory() + ? readdirSync(path) + .filter((name) => name !== "node_modules" && name !== "generated") + .flatMap((name) => walk(join(path, name))) + : /\.tsx?$/.test(path) + ? [relative(ROOT, path)] + : []; + return walk(join(ROOT, dir)); +} + +const FILES = [ + "app/src", + "app/tests", + "extension/src", + "extension/tests", + "desktop/src", + "desktop/workbench", +].flatMap(sourceFiles); + +/** The modules a file imports, from its `import … from` and `import(…)`. */ +function imports(file: string): string[] { + const source = readFileSync(join(ROOT, file), "utf8"); + return [ + ...source.matchAll( + /\bfrom\s+["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']/g, + ), + ].map((match) => match[1] ?? match[2]); +} + +describe("one icon set", () => { + test("no file imports another icon set", () => { + const other = + /^(@tabler\/|lucide-react|react-icons|@heroicons\/|@phosphor-icons\/)/; + const found = FILES.flatMap((file) => + imports(file) + .filter((name) => other.test(name)) + .map((name) => `${file}: ${name}`), + ); + expect(found).toEqual([]); + }); + + test("only the two icon modules import the set", () => { + const found = FILES.filter((file) => + imports(file).some((name) => name.startsWith("@hugeicons/")), + ); + expect(found.sort()).toEqual([APP_ICONS, DESKTOP_ICONS]); + }); + + test("no app depends on another icon set", () => { + for (const app of ["app", "extension", "desktop"]) { + const manifest = JSON.parse( + readFileSync(join(ROOT, app, "package.json"), "utf8"), + ); + const names = Object.keys({ + ...manifest.dependencies, + ...manifest.devDependencies, + }); + expect({ + app, + tabler: names.filter((n) => n.startsWith("@tabler/")), + }).toEqual({ + app, + tabler: [], + }); + expect({ + app, + set: names.includes("@hugeicons/core-free-icons"), + }).toEqual({ + app, + set: true, + }); + } + }); + + /* + * Desktop can't import the web app's module, so it keeps its own. An icon both draw is the same + * glyph in both, so a Bot or a cloud looks the same in the Mac app's setup window and in the app. + */ + test("an icon Desktop shares with the web app is the same glyph", () => { + const glyphs = (file: string) => + new Map( + [ + ...readFileSync(join(ROOT, file), "utf8").matchAll( + /export const (Icon\w+) = defineIcon\(\s*"[^"]+",\s*(\w+)/g, + ), + ].map((match) => [match[1], match[2]]), + ); + const app = glyphs(APP_ICONS); + const desktop = glyphs(DESKTOP_ICONS); + expect(desktop.size).toBeGreaterThan(0); + const differ = [...desktop] + .filter(([name, glyph]) => app.has(name) && app.get(name) !== glyph) + .map( + ([name, glyph]) => + `${name}: ${glyph} in Desktop, ${app.get(name)} in the app`, + ); + expect(differ).toEqual([]); + }); +}); diff --git a/app/tests/model-picker.test.tsx b/app/tests/model-picker.test.tsx index e12860b39f..384e838c4a 100644 --- a/app/tests/model-picker.test.tsx +++ b/app/tests/model-picker.test.tsx @@ -201,9 +201,7 @@ test("the trigger is a CPU icon, and names a model that takes no effort on its o // No name and no maker's mark in the row: the CPU icon and a chevron, named for screen readers. expect(trigger.textContent).toBe(""); expect(trigger.querySelector("img")).toBeNull(); - expect(trigger.firstElementChild?.classList.contains("tabler-icon-cpu")).toBe( - true, - ); + expect(trigger.firstElementChild?.classList.contains("icon-cpu")).toBe(true); }); /** The open popup of a picker drawn on its own. */ @@ -228,7 +226,7 @@ test("a model whose maker has no mark vendored gets the app's plain model icon i const row = within(popup).getByRole("option", { name: "fast" }); // No brand mark is invented for it, and the app's own icon holds the place. expect(row.querySelector("img")).toBeNull(); - expect(row.querySelector("svg.tabler-icon-cube")).not.toBeNull(); + expect(row.querySelector("svg.icon-cube")).not.toBeNull(); }); test("Google and xAI models carry their makers' marks in the list", async () => { diff --git a/app/tests/needs-you.test.tsx b/app/tests/needs-you.test.tsx index bf95a151c7..8362508a7b 100644 --- a/app/tests/needs-you.test.tsx +++ b/app/tests/needs-you.test.tsx @@ -655,7 +655,7 @@ test("a task the person stopped reads Stopped on the board, in its card's words, surface.getByText(title).closest("[data-slot=item]") as HTMLElement; expect(row("Chase the supplier").dataset.taskState).toBe("stopped"); expect( - row("Chase the supplier").querySelector(".tabler-icon-player-stop"), + row("Chase the supplier").querySelector(".icon-player-stop"), ).not.toBeNull(); expect( row("Chase the supplier").querySelector(".bg-warning\\/10"), diff --git a/app/tests/office-file-cards.test.tsx b/app/tests/office-file-cards.test.tsx index cb0a95ee41..ff9de83264 100644 --- a/app/tests/office-file-cards.test.tsx +++ b/app/tests/office-file-cards.test.tsx @@ -46,7 +46,7 @@ const OFFICE = [ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sizeBytes: 14_336, label: "Excel workbook · 14 KB", - icon: "tabler-icon-file-type-xls", + icon: "icon-file-type-xls", }, { name: "launch memo.docx", @@ -54,7 +54,7 @@ const OFFICE = [ "application/vnd.openxmlformats-officedocument.wordprocessingml.document", sizeBytes: 48_128, label: "Word document · 47 KB", - icon: "tabler-icon-file-type-docx", + icon: "icon-file-type-docx", }, { name: "board deck.pptx", @@ -62,7 +62,7 @@ const OFFICE = [ "application/vnd.openxmlformats-officedocument.presentationml.presentation", sizeBytes: 3_250_586, label: "PowerPoint presentation · 3.1 MB", - icon: "tabler-icon-file-type-ppt", + icon: "icon-file-type-ppt", }, ] as const; diff --git a/app/tests/organization-menu-names.fixture.tsx b/app/tests/organization-menu-names.fixture.tsx index 308a468315..4c46e11f82 100644 --- a/app/tests/organization-menu-names.fixture.tsx +++ b/app/tests/organization-menu-names.fixture.tsx @@ -1,4 +1,4 @@ -import { IconLogout, IconSettings } from "@tabler/icons-react"; +import { IconLogout, IconSettings } from "@/components/icons"; import { QueryClientProvider } from "@tanstack/react-query"; import { createMemoryHistory, diff --git a/app/tests/personal-connections.test.tsx b/app/tests/personal-connections.test.tsx index 8d22501a66..7b80cc6796 100644 --- a/app/tests/personal-connections.test.tsx +++ b/app/tests/personal-connections.test.tsx @@ -444,7 +444,7 @@ test("a search that matches nothing says No matches, with no sections and no dir expect(await view.findByText("No matches")).toBeTruthy(); expect(view.getByText("Nothing matches “zzzz”.")).toBeTruthy(); expect( - view.container.querySelector(".tabler-icon-search:not([aria-hidden])"), + view.container.querySelector(".icon-search:not([aria-hidden])"), ).not.toBeNull(); expect(view.queryByTestId("account-browse")).toBeNull(); expect(view.queryByRole("heading", { name: "Your apps" })).toBeNull(); diff --git a/app/tests/roster-working.fixture.tsx b/app/tests/roster-working.fixture.tsx index 85eb51b372..983e7e77b2 100644 --- a/app/tests/roster-working.fixture.tsx +++ b/app/tests/roster-working.fixture.tsx @@ -1,4 +1,4 @@ -import { IconMessages, IconRobot } from "@tabler/icons-react"; +import { IconMessages, IconRobot } from "@/components/icons"; import { QueryClientProvider } from "@tanstack/react-query"; import { createBrowserHistory, diff --git a/app/tests/routine-box-line.test.tsx b/app/tests/routine-box-line.test.tsx index 5f4bdaf6fe..63add987e2 100644 --- a/app/tests/routine-box-line.test.tsx +++ b/app/tests/routine-box-line.test.tsx @@ -265,7 +265,7 @@ test("no line has a Dismiss or a close button", async () => { const view = draw(line); await view.findByRole("status"); expect(view.queryByRole("button", { name: /dismiss|close/i })).toBeNull(); - expect(view.container.querySelector("svg.tabler-icon-x")).toBeNull(); + expect(view.container.querySelector("svg.icon-x")).toBeNull(); cleanup(); } }); diff --git a/app/tests/routines-bot-group.test.tsx b/app/tests/routines-bot-group.test.tsx index 3534e2fdfe..514020e6c7 100644 --- a/app/tests/routines-bot-group.test.tsx +++ b/app/tests/routines-bot-group.test.tsx @@ -160,7 +160,7 @@ test("a routine that is off shows the pause icon even when its last run failed", const fact = await view.findByText(/^Failed /); const row = fact.closest("a"); expect(row?.querySelector("svg")?.getAttribute("class")).toContain( - "tabler-icon-player-pause", + "icon-player-pause", ); expect(row?.className).not.toContain("opacity-60"); }); diff --git a/app/tests/routines-merged.test.tsx b/app/tests/routines-merged.test.tsx index f5516ea4d3..ee67526f50 100644 --- a/app/tests/routines-merged.test.tsx +++ b/app/tests/routines-merged.test.tsx @@ -536,7 +536,7 @@ test("every kind of row is one link or button with a chevron, with no control in const row = view.getByText(text).closest("a, button") as HTMLElement; expect(row).not.toBeNull(); expect(row.querySelector("button, a, input, [role=switch]")).toBeNull(); - expect(row.querySelector(".tabler-icon-chevron-right")).not.toBeNull(); + expect(row.querySelector(".icon-chevron-right")).not.toBeNull(); } expect(view.queryByRole("switch")).toBeNull(); expect(view.queryByRole("button", { name: /^Delete/ })).toBeNull(); diff --git a/app/tests/screen-link-style.ts b/app/tests/screen-link-style.ts index c7cbfbe066..4f088accf9 100644 --- a/app/tests/screen-link-style.ts +++ b/app/tests/screen-link-style.ts @@ -43,7 +43,7 @@ export function screenLinkLooks( href: link.getAttribute("href") ?? "", underlined: style.textDecorationLine.includes("underline"), chevron: Boolean( - svg?.classList.contains("tabler-icon-chevron-right") && + svg?.classList.contains("icon-chevron-right") && svg.getBoundingClientRect().left >= link.getBoundingClientRect().left + link.getBoundingClientRect().width / 2, diff --git a/app/tests/settings-tool-cards-core.test.tsx b/app/tests/settings-tool-cards-core.test.tsx index 67125880d0..a09172e82e 100644 --- a/app/tests/settings-tool-cards-core.test.tsx +++ b/app/tests/settings-tool-cards-core.test.tsx @@ -461,7 +461,7 @@ describe.skipIf(!asked)("the settings read cards", () => { ].map( (row) => row.lastElementChild?.classList.contains( - "tabler-icon-chevron-right", + "icon-chevron-right", ) ?? false, ), ), diff --git a/app/tests/sidebar-window-buttons.fixture.tsx b/app/tests/sidebar-window-buttons.fixture.tsx index 5fc8b627b7..6da407c81b 100644 --- a/app/tests/sidebar-window-buttons.fixture.tsx +++ b/app/tests/sidebar-window-buttons.fixture.tsx @@ -1,4 +1,4 @@ -import { IconSettings } from "@tabler/icons-react"; +import { IconSettings } from "@/components/icons"; import { QueryClientProvider } from "@tanstack/react-query"; import { createMemoryHistory, diff --git a/app/tests/sidebar-zoom-drag.fixture.tsx b/app/tests/sidebar-zoom-drag.fixture.tsx index e25125513a..35e61dce40 100644 --- a/app/tests/sidebar-zoom-drag.fixture.tsx +++ b/app/tests/sidebar-zoom-drag.fixture.tsx @@ -1,4 +1,4 @@ -import { IconMessages, IconRobot } from "@tabler/icons-react"; +import { IconMessages, IconRobot } from "@/components/icons"; import { QueryClientProvider } from "@tanstack/react-query"; import { createBrowserHistory, diff --git a/app/tests/stopped-connection-notice.test.tsx b/app/tests/stopped-connection-notice.test.tsx index 7942f0d75c..44c145e6ec 100644 --- a/app/tests/stopped-connection-notice.test.tsx +++ b/app/tests/stopped-connection-notice.test.tsx @@ -380,15 +380,13 @@ test("the trigger shows the warning mark while stopped is set, and none after th ); const trigger = view.getByRole("combobox", { name: /GPT-6.2 Sol/ }); expect(trigger.getAttribute("aria-label")).toContain("can't run now"); - expect( - trigger.querySelector("svg.tabler-icon-alert-triangle"), - ).not.toBeNull(); + expect(trigger.querySelector("svg.icon-alert-triangle")).not.toBeNull(); view.rerender( {}} value={pick} />, ); const after = view.getByRole("combobox", { name: /GPT-6.2 Sol/ }); expect(after.getAttribute("aria-label")).not.toContain("can't run now"); - expect(after.querySelector("svg.tabler-icon-alert-triangle")).toBeNull(); + expect(after.querySelector("svg.icon-alert-triangle")).toBeNull(); }); const NO_DEFAULT = "Choose a default AI in Settings so Bots can start work."; diff --git a/app/tests/strip.test.tsx b/app/tests/strip.test.tsx index dcf2284d1a..cf04f5b1dc 100644 --- a/app/tests/strip.test.tsx +++ b/app/tests/strip.test.tsx @@ -1,6 +1,6 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; -import { IconBolt, IconMessages } from "@tabler/icons-react"; +import { IconBolt, IconMessages } from "@/components/icons"; import { cleanup, render, within } from "@testing-library/react"; import type { ReactNode } from "react"; import { SectionPanel } from "@/components/layout/section-panel"; diff --git a/app/tests/team-models-screens-layout.test.tsx b/app/tests/team-models-screens-layout.test.tsx index a472238dfc..166f4c05fd 100644 --- a/app/tests/team-models-screens-layout.test.tsx +++ b/app/tests/team-models-screens-layout.test.tsx @@ -755,9 +755,7 @@ describe.skipIf(!asked)("a team's models", () => { await modelsRow(page).evaluate((row) => row.tagName), ).not.toBe("BUTTON"); expect( - await modelsRow(page) - .locator("svg.tabler-icon-chevron-right") - .count(), + await modelsRow(page).locator("svg.icon-chevron-right").count(), ).toBe(0); await look(page, `team-page-member-${tag}`); } finally { diff --git a/app/tests/transcript-attachments.test.tsx b/app/tests/transcript-attachments.test.tsx index 38177f6dd1..b0b5cae7b1 100644 --- a/app/tests/transcript-attachments.test.tsx +++ b/app/tests/transcript-attachments.test.tsx @@ -517,7 +517,7 @@ test("an Office file a person sent is drawn as its kind, with its size and a dow "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sizeBytes: 14_336, label: "Excel workbook · 14 KB", - icon: "tabler-icon-file-type-xls", + icon: "icon-file-type-xls", }, { filename: "memo.docx", @@ -525,7 +525,7 @@ test("an Office file a person sent is drawn as its kind, with its size and a dow "application/vnd.openxmlformats-officedocument.wordprocessingml.document", sizeBytes: 2_411_724, label: "Word document · 2.3 MB", - icon: "tabler-icon-file-type-docx", + icon: "icon-file-type-docx", }, { filename: "deck.pptx", @@ -533,7 +533,7 @@ test("an Office file a person sent is drawn as its kind, with its size and a dow "application/vnd.openxmlformats-officedocument.presentationml.presentation", sizeBytes: 31_457_280, label: "PowerPoint presentation · 30 MB", - icon: "tabler-icon-file-type-ppt", + icon: "icon-file-type-ppt", }, ]; const { container, getByRole, getByText, queryByText } = renderTranscript([ diff --git a/app/tests/ui-look-theme.test.ts b/app/tests/ui-look-theme.test.ts index ba6f681959..66dd6aff58 100644 --- a/app/tests/ui-look-theme.test.ts +++ b/app/tests/ui-look-theme.test.ts @@ -1,9 +1,12 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import * as icons from "../src/components/icons"; /* * The two theme values the web app's look changes (docs/app-guidelines.md, "The look"): corners - * from an 8px radius, and the default icon line at 1.75. The scheme's generated block is held to + * from an 8px radius, and every icon at the icon set's 1.5 line. The scheme's generated block is held to * tokens/src/scheme.ts by tokens/tests/generated.test.ts, not here. */ @@ -17,19 +20,32 @@ describe("the look's theme values", () => { expect(root?.[1]).toMatch(/--radius:\s*0\.5rem;/); }); - test("the default icon stroke is 1.75, and only the default", () => { - const rules = [ - ...withoutComments.matchAll(/([^{}]*\.tabler-icon[^{}]*)\{([^}]*)\}/g), - ].map((match) => ({ - selector: match[1].trim(), - body: match[2].trim(), - })); - expect(rules).toEqual([ - { - selector: '.tabler-icon[stroke-width="2"]', - body: "stroke-width: 1.75;", - }, - ]); + /* + * Hugeicons' glyphs carry their line on each element, at 1.5 on a 24-unit grid. Every icon draws + * that line unless it is given its own `stroke`, and no rule in the theme draws it otherwise. + */ + test("every icon draws the set's 1.5 line, and its own when given one", () => { + const drawn = Object.entries(icons).filter(([name]) => + /^Icon[A-Z]/.test(name), + ) as [string, icons.Icon][]; + expect(drawn.length).toBeGreaterThan(200); + const lines = (icon: icons.Icon, stroke?: number) => [ + ...new Set( + [ + ...renderToStaticMarkup(createElement(icon, { stroke })).matchAll( + /stroke-width="([^"]+)"/g, + ), + ].map((match) => match[1]), + ), + ]; + for (const [name, icon] of drawn) { + expect({ name, lines: lines(icon) }).toEqual({ name, lines: ["1.5"] }); + expect({ name, lines: lines(icon, 2) }).toEqual({ name, lines: ["2"] }); + } + }); + + test("no rule in the theme sets an icon's line", () => { + expect(withoutComments).not.toContain("stroke-width"); }); /* diff --git a/app/tests/vault.test.tsx b/app/tests/vault.test.tsx index 6406812959..63aa4e0012 100644 --- a/app/tests/vault.test.tsx +++ b/app/tests/vault.test.tsx @@ -136,7 +136,7 @@ describe("the Vault", () => { const media = row.querySelector( "[data-slot=item-media][data-variant=icon]", ); - expect({ name, icon: media?.querySelector(".tabler-icon-key") }).toEqual({ + expect({ name, icon: media?.querySelector(".icon-key") }).toEqual({ name, icon: expect.anything(), }); diff --git a/app/tests/web-push.fixture.tsx b/app/tests/web-push.fixture.tsx index f1953afcd4..e0a7fa1945 100644 --- a/app/tests/web-push.fixture.tsx +++ b/app/tests/web-push.fixture.tsx @@ -1,4 +1,4 @@ -import { IconPlayerPause } from "@tabler/icons-react"; +import { IconPlayerPause } from "@/components/icons"; import { QueryClientProvider } from "@tanstack/react-query"; import { createBrowserHistory, diff --git a/biome.json b/biome.json index 2c9636258d..27a965f411 100644 --- a/biome.json +++ b/biome.json @@ -66,7 +66,7 @@ "@/lib/client", "@/query-client" ], - "message": "The extension runs in the browser. It talks to OpenBot over HTTP only, and takes only OpenBot's UI primitives and layout parts from the app." + "message": "The extension runs in the browser. It talks to OpenBot over HTTP only, and takes only OpenBot's UI primitives, icons and layout parts from the app." } ] } diff --git a/bun.lock b/bun.lock index ee229fde7a..02d290a6a5 100644 --- a/bun.lock +++ b/bun.lock @@ -29,11 +29,12 @@ "@better-auth/sso": "^1.7.1", "@copilotkit/react-core": "1.88.0", "@fontsource-variable/figtree": "^5.3.0", + "@hugeicons/core-free-icons": "^4.4.0", + "@hugeicons/react": "^1.1.10", "@openbot/shared": "workspace:*", "@shadcn/react": "^0.3.0", "@streamdown/code": "2.0.0", "@streamdown/math": "1.0.3", - "@tabler/icons-react": "^3.36.1", "@tanstack/react-form": "^1.33.5", "@tanstack/react-hotkeys": "^0.10.0", "@tanstack/react-query": "^5.101.4", @@ -88,9 +89,10 @@ "@copilotkit/learning": "1.85.0", "@fontsource-variable/figtree": "^5.3.0", "@happy-dom/global-registrator": "^20.11.2", + "@hugeicons/core-free-icons": "^4.4.0", + "@hugeicons/react": "^1.1.10", "@openbot/shared": "workspace:*", "@openbot/tokens": "workspace:*", - "@tabler/icons-react": "^3.36.1", "@tailwindcss/vite": "^4.3.3", "@testing-library/react": "^16.3.2", "@testing-library/user-event": "^14.6.4", @@ -448,6 +450,10 @@ "@hono/node-server": ["@hono/node-server@1.19.17", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ=="], + "@hugeicons/core-free-icons": ["@hugeicons/core-free-icons@4.4.0", "", {}, "sha512-7Mz8bmGoY6tZ6l3C2TXwNMLVSr0I8HPwjjFIERAuJFj3rWwLxdF2ZLkDqdrVuEE1dx5b/VXyIsP4WoSU6Q40KQ=="], + + "@hugeicons/react": ["@hugeicons/react@1.1.10", "", { "peerDependencies": { "react": ">=16.0.0" } }, "sha512-9tAsd92yMVVGP+E+d8cM+wc0VnXuYZHNbWQi7TOe8k2neawmhiaFmVFbzyruejhOMa197/LbgvSED32ayUo3ZA=="], + "@iconify/types": ["@iconify/types@2.0.0", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="], "@iconify/utils": ["@iconify/utils@3.1.4", "", { "dependencies": { "@antfu/install-pkg": "^1.1.0", "@iconify/types": "^2.0.0", "import-meta-resolve": "^4.2.0" } }, "sha512-b1S7B1k9ohZ+iNTi2ATxbRYG9fTrJmUT0rc46bvVnNxqNRGW7dyo/vRREwyniI5IRN2RSJHDcm+s3BjWrSAjHw=="], @@ -780,10 +786,6 @@ "@streamdown/math": ["@streamdown/math@1.0.3", "", { "dependencies": { "katex": "^0.16.27", "rehype-katex": "^7.0.1", "remark-math": "^6.0.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-TOTRlPYs4LBNT8GaIWNCEVrcGVQsVcfc8WZ/x/0IyO+Rvsu6W+nF+YCS4Pl3JTVWQK8QX7LbWUChSilwlyzPZw=="], - "@tabler/icons": ["@tabler/icons@3.46.0", "", {}, "sha512-f2RYFl3fzPwj5WO82x6en0dmkjefxEfOm16D1ByM6cj/McNiwOkL4VaPUoP9VVIrXAD9WnTSVFr70px703b//A=="], - - "@tabler/icons-react": ["@tabler/icons-react@3.46.0", "", { "dependencies": { "@tabler/icons": "3.46.0" }, "peerDependencies": { "react": ">= 16" } }, "sha512-CCm7xJWhDT2PH4ZIFkP6AgYKtVhq0gpYkjUN+GVh1AzmIQaa77OW0bQPBPQiTE0PsXMR9oSxFqA3qBglzPyrVQ=="], - "@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="], "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.3", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="], diff --git a/desktop/bun.lock b/desktop/bun.lock index a06d786d7d..6f3e3605cd 100644 --- a/desktop/bun.lock +++ b/desktop/bun.lock @@ -6,7 +6,8 @@ "name": "openbot-desktop", "dependencies": { "@fontsource-variable/figtree": "5.3.0", - "@tabler/icons-react": "3.46.0", + "@hugeicons/core-free-icons": "4.4.0", + "@hugeicons/react": "1.1.10", "@tauri-apps/api": "^2.12.4", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -124,6 +125,10 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.14.0", "", { "dependencies": { "@types/node": ">=20.0.0", "happy-dom": "^20.14.0" } }, "sha512-Xn0kdkaA1eHOaFFopr+YQ37sPNTZ3JScpUMz3j4rIsn1Nneqoh94z79iW23Ej0Ytt99+LlFr4JrSDd6ow9c7MQ=="], + "@hugeicons/core-free-icons": ["@hugeicons/core-free-icons@4.4.0", "", {}, "sha512-7Mz8bmGoY6tZ6l3C2TXwNMLVSr0I8HPwjjFIERAuJFj3rWwLxdF2ZLkDqdrVuEE1dx5b/VXyIsP4WoSU6Q40KQ=="], + + "@hugeicons/react": ["@hugeicons/react@1.1.10", "", { "peerDependencies": { "react": ">=16.0.0" } }, "sha512-9tAsd92yMVVGP+E+d8cM+wc0VnXuYZHNbWQi7TOe8k2neawmhiaFmVFbzyruejhOMa197/LbgvSED32ayUo3ZA=="], + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], @@ -188,10 +193,6 @@ "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.63.1", "", { "os": "win32", "cpu": "x64" }, "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w=="], - "@tabler/icons": ["@tabler/icons@3.46.0", "", {}, "sha512-f2RYFl3fzPwj5WO82x6en0dmkjefxEfOm16D1ByM6cj/McNiwOkL4VaPUoP9VVIrXAD9WnTSVFr70px703b//A=="], - - "@tabler/icons-react": ["@tabler/icons-react@3.46.0", "", { "dependencies": { "@tabler/icons": "3.46.0" }, "peerDependencies": { "react": ">= 16" } }, "sha512-CCm7xJWhDT2PH4ZIFkP6AgYKtVhq0gpYkjUN+GVh1AzmIQaa77OW0bQPBPQiTE0PsXMR9oSxFqA3qBglzPyrVQ=="], - "@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="], "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.3", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="], diff --git a/desktop/package.json b/desktop/package.json index 2b2c2f9c7e..3cd6414981 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -13,7 +13,8 @@ }, "dependencies": { "@fontsource-variable/figtree": "5.3.0", - "@tabler/icons-react": "3.46.0", + "@hugeicons/core-free-icons": "4.4.0", + "@hugeicons/react": "1.1.10", "@tauri-apps/api": "^2.12.4", "react": "^19.2.0", "react-dom": "^19.2.0" diff --git a/desktop/src/BusinessBooker.tsx b/desktop/src/BusinessBooker.tsx index db98dfc3a7..9e87770ee1 100644 --- a/desktop/src/BusinessBooker.tsx +++ b/desktop/src/BusinessBooker.tsx @@ -14,7 +14,7 @@ import { IconSparkles, IconUsers, IconUsersGroup, -} from "@tabler/icons-react"; +} from "./icons"; import { type ReactNode, type Ref, diff --git a/desktop/src/CopilotKitAccount.tsx b/desktop/src/CopilotKitAccount.tsx index 4034f0b0e0..21c32f3140 100644 --- a/desktop/src/CopilotKitAccount.tsx +++ b/desktop/src/CopilotKitAccount.tsx @@ -1,4 +1,4 @@ -import { IconFileText } from "@tabler/icons-react"; +import { IconFileText } from "./icons"; import { type ReactNode, useCallback, diff --git a/desktop/src/EndpointMark.tsx b/desktop/src/EndpointMark.tsx index d29fea3df9..a45c300426 100644 --- a/desktop/src/EndpointMark.tsx +++ b/desktop/src/EndpointMark.tsx @@ -1,8 +1,8 @@ -import { IconCloud } from "@tabler/icons-react"; +import { IconCloud } from "./icons"; /** - * The tile for "Any OpenAI-compatible endpoint": Tabler's cloud, the icon OpenBot's admin page gives - * the same source. + * The tile for "Any OpenAI-compatible endpoint": the icon set's cloud, the icon OpenBot's admin page + * gives the same source. * * An endpoint is nobody's, so no vendor's mark belongs here (see shared/marks/README.md). Without a * tile, though, it was the one row in the list with nothing beside its name. This is the marks' own @@ -13,7 +13,7 @@ import { IconCloud } from "@tabler/icons-react"; export function EndpointMark() { return ( ); } diff --git a/desktop/src/MoveToCloud.tsx b/desktop/src/MoveToCloud.tsx index b541347040..1a22f891ad 100644 --- a/desktop/src/MoveToCloud.tsx +++ b/desktop/src/MoveToCloud.tsx @@ -14,7 +14,7 @@ import { IconRobot, IconTarget, IconUser, -} from "@tabler/icons-react"; +} from "./icons"; import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { @@ -780,7 +780,7 @@ function Sheet({ children }: { children: ReactNode }) { function Mark({ icon: Glyph }: { icon: Icon }) { return ( ); } @@ -840,7 +840,7 @@ function Choice({ onChange={() => setPicked("business")} /> - + OpenBot for Business {BUSINESS_SUMMARY} @@ -1020,7 +1020,7 @@ function Confirm({
      {lines.map((line) => (
    • -
    • ))} @@ -1156,7 +1156,7 @@ function AppMark({ app }: { app: ReconnectApp }) { {app.iconUrl && !broken ? ( setBroken(true)} /> ) : ( - + )} ); @@ -1209,7 +1209,7 @@ function Done({ moved }: { moved: Moved }) {

      {moved.removedBytes != null && moved.removedBytes > 0 && (
      -