Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(mobile): support global and custom phone model selection
trohitgf2359ba665ae
diff --git a/CLAUDE.md b/CLAUDE.mdindex e390bd37..607abf26 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1721,7 +1721,7 @@ Toolkit aggregator nodes (the former `androidTool` and its `TOOLKIT_NODE_TYPES`### Local emulator workspace (separate plugin)-`server/nodes/mobile/` owns **Mobile Agent** (`mobile_use_agent`) and the **Android** tool (`android_tool`). Both declare `ui_hints.workspace.kind="mobile"`; Home and Dev render `MobileWorkspace`. Android's Tool output connects to an agent's Tools input and requires its own Model connection. Its AI-visible schema contains only `prompt`; saved configuration controls time/step limits. This plugin does not replace the relay services documented below.+`server/nodes/mobile/` owns **Mobile Agent** (`mobile_use_agent`) and the **Android** tool (`android_tool`). Both declare `ui_hints.workspace.kind="mobile"`; Home and Dev render `MobileWorkspace`. Android’s Tool output connects to an agent’s Tools input. Both phone nodes follow the saved global model by default; custom settings override it, and a connected Model node takes highest priority. Its AI-visible schema contains only `prompt`; saved configuration controls time/step limits. This plugin does not replace the relay services documented below.Startup must hold `driver_lock` while reading the initialization reply; regular commands use the same lock. `/status` must skip driver I/O during lifecycle transitions. A serial alone does not mean the phone is ready. Keep connection warnings separate from action errors and clear them after successful polling.diff --git a/client/src/components/mobile/MobileWorkspace.tsx b/client/src/components/mobile/MobileWorkspace.tsxindex ed2efce8..9805fe1c 100644--- a/client/src/components/mobile/MobileWorkspace.tsx+++ b/client/src/components/mobile/MobileWorkspace.tsx@@ -248,7 +248,7 @@ function MobileSession({ workflowId, nodeId, visible }: { workflowId: string; no<form className="mt-auto flex shrink-0 flex-col group-data-[full-view=true]/fullview:hidden gap-2 border-t border-border-default pt-3" onSubmit={(event) => { event.preventDefault(); void submit(); }}><label htmlFor={`task-${nodeId}`} className="text-sm font-medium">Ask AI to use the phone</label><textarea id={`task-${nodeId}`} className={`${fieldClass} resize-y`} rows={2} maxLength={12000} value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder="For example: Open Settings and turn on dark mode" />- <p className="m-0 text-xs text-fg-muted">Tell the AI what you want done. Only one person or AI can use this phone at a time.</p>+ <p className="m-0 text-xs text-fg-muted">Uses your global AI model unless this phone has a model override. Only one person or AI can use the phone at a time.</p><div className="flex items-center gap-2"><Button size="sm" type="submit" disabled={!running || !prompt.trim() || !!busy || hasTask}>Run task</Button>{hasTask && <Button size="sm" type="button" variant="outline" disabled={!!busy} onClick={() => void perform('cancelling', async () => { setTask(await mobileRequest(`${path}/tasks/${encodeURIComponent(submission!)}/cancel`, {})); })}>Cancel task</Button>}{task && <span role="status" className="text-xs text-fg-muted">{({queued: 'Waiting for the phone', running: 'Working on your request', completed: 'Done', failed: 'Could not finish', cancelled: 'Cancelled', awaiting_user: 'Waiting for you'})[taskState(task)] || 'Request received'}</span>}diff --git a/client/src/components/ui/__tests__/WorkspaceDock.test.tsx b/client/src/components/ui/__tests__/WorkspaceDock.test.tsxindex d7d32948..8af7f924 100644--- a/client/src/components/ui/__tests__/WorkspaceDock.test.tsx+++ b/client/src/components/ui/__tests__/WorkspaceDock.test.tsx@@ -32,14 +32,14 @@ beforeEach(() => {});describe('Developer workspace', () => {- it('shares Browser, Canvas and Android tabs and the workflow-bound viewer', () => {+ it('shares Browser, Canvas and Mobile tabs and the workflow-bound viewer', () => {render(<CanvasDock nodes={nodes} />);expect(screen.getByText('Saved canvas board')).toBeInTheDocument();fireEvent.mouseDown(screen.getByRole('tab', { name: 'Browser' }), { button: 0, ctrlKey: false });expect(screen.getByText('Research browser')).toBeInTheDocument();expect(screen.getByTestId('browser-view')).toHaveAttribute('data-workflow', 'wf1');- fireEvent.mouseDown(screen.getByRole('tab', { name: 'Android' }), { button: 0, ctrlKey: false });- expect(screen.getByText('The Android mirror isn’t available yet')).toBeInTheDocument();+ fireEvent.mouseDown(screen.getByRole('tab', { name: 'Mobile' }), { button: 0, ctrlKey: false });+ expect(screen.getByText('Add a Mobile Agent or Android tool to this workflow to use its phone here.')).toBeInTheDocument();expect(screen.queryByTestId('browser-view')).toBeNull();});diff --git a/client/src/features/home/__tests__/workspace.test.tsx b/client/src/features/home/__tests__/workspace.test.tsxindex ba6f65a4..93af1f15 100644--- a/client/src/features/home/__tests__/workspace.test.tsx+++ b/client/src/features/home/__tests__/workspace.test.tsx@@ -168,7 +168,7 @@ describe('WorkspaceDock', () => {expect(screen.getByTestId('browser-workspace')).toHaveAttribute('data-workflow', 'w1');expect(screen.getByTestId('browser-workspace')).toHaveAttribute('data-visible', 'true');await userEvent.click(screen.getByRole('tab', { name: 'Mobile' }));- expect(screen.getByText('Add a Mobile Agent node to this workflow to use its phone here.')).toBeInTheDocument();+ expect(screen.getByText('Add a Mobile Agent or Android tool to this workflow to use its phone here.')).toBeInTheDocument();expect(useHomeStore.getState().workspaceTab).toBe('android');expect(screen.queryByTestId('browser-workspace')).toBeNull();});diff --git a/docs-internal/node-logic-flows/mobile/android_tool.md b/docs-internal/node-logic-flows/mobile/android_tool.mdindex 7f48e98d..dd6c44ed 100644--- a/docs-internal/node-logic-flows/mobile/android_tool.md+++ b/docs-internal/node-logic-flows/mobile/android_tool.md@@ -15,13 +15,15 @@ Give an existing AI agent a natural-language tool for the shared local Android p| Handle | Required | Purpose || --- | --- | --- |-| `input-model` | Yes | Exactly one enabled OpenAI, Anthropic, or Gemini model connector for the embedded mobile-use engine |+| `input-model` | No | Optional single enabled OpenAI, Anthropic, or Gemini model connector overriding node/global selection for the embedded mobile-use engine |## ParametersThe AI-visible schema accepts only `prompt`: a required string, 1–20,000 characters. Whitespace-only requests are rejected by the shared execution path. Extra tool arguments are forbidden.-Saved configuration uses `MobileParams`: `prompt` defaults to empty, `max_steps` defaults to 40 (1–200), and `timeout_s` defaults to 900 (30–3600 seconds). In tool mode, the model supplies the request while the saved configuration controls the step/time limits. A parent agent's model connection does not replace `input-model` on this node.+Saved configuration uses `MobileParams`: `prompt` defaults to empty, `max_steps` defaults to 40 (1–200), and `timeout_s` defaults to 900 (30–3600 seconds). In tool mode, the model supplies the request while the saved configuration controls the step/time limits. The global model is used by default; a parent agent’s custom model is not inherited automatically.++Model selection defaults to `model_source="global"`, reading the toolbar’s current saved provider/model on each task. `model_source="custom"` uses the node’s `provider` and `model`; blank custom model uses the provider default. One connected model takes priority over both modes. Missing or unsupported global providers produce actionable errors. Supported providers are OpenAI, Anthropic and Gemini.## Outputs (handles)diff --git a/docs-internal/node-logic-flows/mobile/mobile_use_agent.md b/docs-internal/node-logic-flows/mobile/mobile_use_agent.mdindex 31ebf543..4257d033 100644--- a/docs-internal/node-logic-flows/mobile/mobile_use_agent.md+++ b/docs-internal/node-logic-flows/mobile/mobile_use_agent.md@@ -16,7 +16,7 @@ Carry out direct Workspace requests or delegated employee tasks on one persisten| Handle | Required | Purpose || --- | --- | --- || `input-main` | No | Task/main workflow input |-| `input-model` | Yes | Exactly one enabled OpenAI, Anthropic, or Gemini model connector |+| `input-model` | No | Optional single enabled OpenAI, Anthropic, or Gemini model connector overriding node/global selection || `input-context` | No | Context connection |## Parameters@@ -27,6 +27,8 @@ Carry out direct Workspace requests or delegated employee tasks on one persisten| `max_steps` | 40 | 1–200 || `timeout_s` | 900 | 30–3600 seconds of active task time |+Model selection defaults to `model_source="global"`, reading the toolbar’s current saved provider/model on each task. `model_source="custom"` uses the node’s `provider` and `model`; blank custom model uses the provider default. One connected model takes priority over both modes. Missing or unsupported global providers produce actionable errors. Supported providers are OpenAI, Anthropic and Gemini.+## Outputs (handles)`output-main` returns the action result; `output-top` is the **Delegate** connection. The result payload contains `response`, `outcome`, `run_id`, and `artifacts` (currently empty), within the standard action envelope.diff --git a/docs/mobile-workspace.md b/docs/mobile-workspace.mdindex e9b779fc..0e7c7602 100644--- a/docs/mobile-workspace.md+++ b/docs/mobile-workspace.md@@ -17,7 +17,7 @@ The runtime singleton and its leases are process-local. Run one backend process3. Review and accept the Android SDK license in setup. Setup installs the optional engine and Android packages and creates the persistent `OpenCompany` AVD using a Pixel 7 device profile. Network access and sufficient disk space are required for these downloads.4. Click **Start phone** and wait for **Ready**. The emulator runs without a separate desktop window; the Workspace shows its video. Device storage persists across stopping and starting the emulator.5. Click **Use phone** to sign in to the Play Store, install applications, or upload an APK. APK uploads are limited to 256 MB and require the current manual-control lease. Play Store availability comes from the selected Google Play system image; account sign-in is performed on the device.-6. Connect a provider in OpenCompany Settings, then connect exactly one AI model node to the phone node's **Model** input and save the workflow. The model selected on that connector is used for every mobile-use stage. OpenAI, Anthropic, and Gemini credentials are supported. Choose a model with image input and tool use, then enter a request under **Ask AI to use the phone** and click **Run task**, or call the node through its agent connection.+6. Connect a provider in OpenCompany Settings, then choose a supported global model in the toolbar. Phone nodes use it by default. For an override, choose **Custom** under the node’s **Model selection**, or connect exactly one model to its **Model** input. Save the workflow. The resolved model is used for every mobile-use stage. OpenAI, Anthropic, and Gemini credentials are supported. Choose a model with image input and tool use, then enter a request under **Ask AI to use the phone** and click **Run task**, or call the node through its agent connection.The setup is optional. Ordinary application startup does not install the mobile engine or boot an emulator. Runtime data lives under the configured OpenCompany data directory's `mobile` subdirectory, including the engine environment, AVD, and device resource metadata. Stopping the emulator does not reset its apps or account sessions.@@ -27,8 +27,8 @@ Setup shows the current component, download or SDK output, elapsed time, last up| Node | Use it for | Connection || --- | --- | --- |-| **Mobile Agent** (`mobile_use_agent`) | Direct Workspace requests or delegated phone tasks | Exactly one model into **Model**; **Delegate** output for employee delegation |-| **Android** (`android_tool`) | Giving an existing AI agent a phone tool | **Tool** output into the agent’s **Tools** input, plus exactly one model into Android’s **Model** input |+| **Mobile Agent** (`mobile_use_agent`) | Direct Workspace requests or delegated phone tasks | Global model by default; optional **Model** override; **Delegate** output for employee delegation |+| **Android** (`android_tool`) | Giving an existing AI agent a phone tool | **Tool** output into the agent’s **Tools** input; global model by default, with an optional **Model** override |Both nodes use the same phone. Adding another node does not create another emulator. The existing `android_agent` and relay service nodes are separate integrations; they do not set up this local phone.@@ -49,6 +49,16 @@ Choose **Full view** above the phone to fill the screen. The live phone expandsConnection warnings clear after a successful status check. Action errors have a **Dismiss** button. Task submission is disabled while the phone is off. Download details, completed setup history, and technical diagnostics are collapsed by default.+## Model selection++Both Mobile Agent and Android use this order:++1. A connected **Model** node overrides all node/global settings. Multiple connections or a disabled/invalid connector produce an error rather than falling back silently.+2. With **Model selection = custom**, the saved phone provider/model is used. An empty model uses that provider’s configured default.+3. With **Model selection = global** (the default), the current toolbar selection is read for every new task. Changing it applies to the next task, not a worker already running.++The selected model serves every mobile-use stage. OpenAI, Anthropic and Gemini are supported. An unsupported or missing global selection gives an actionable error; it never silently selects a different provider. Credentials always come from stored provider settings. Android’s AI-visible tool schema remains prompt-only, so an agent cannot override model selection or saved execution limits through tool arguments.+## Runtime files and Git`mobile_root()` currently resolves a relative `DATA_DIR` against the backend process’s working directory. With source development launched from `server/` and `DATA_DIR=.opencompany`, the installed phone is therefore under `server/.opencompany/mobile/`. This differs from the application’s canonical repository-relative data resolver. An absolute `DATA_DIR` avoids this ambiguity. Do not move an existing installation or switch its data directory while the backend is running.@@ -59,7 +69,7 @@ The repository ignores `server/.opencompany/`. Emulator disks, snapshots, downlo### Android tool for AI agents-Add the **Android** tool node (`android_tool`) and connect its **Tool** output to an AI agent's **Tools** input. Connect an OpenAI, Anthropic, or Gemini model node to Android's **Model** input; the same model node can also feed the parent agent. Save the workflow, then set up and start the phone in Workspace → Mobile. The agent calls `android` with one argument, `prompt`, such as “Open Settings and turn on dark mode.” The tool uses the same mobile-use engine, owner checks, task queue, manual takeover, and saved time/step limits as Mobile Agent. It does not install software or accept licenses automatically.+Add the **Android** tool node (`android_tool`) and connect its **Tool** output to an AI agent's **Tools** input. The tool follows the saved global model by default. Optionally choose a custom model in its settings or connect an OpenAI, Anthropic, or Gemini model node to Android’s **Model** input; a connected model takes priority. Save the workflow, then set up and start the phone in Workspace → Mobile. The agent calls `android` with one argument, `prompt`, such as “Open Settings and turn on dark mode.” The tool uses the same mobile-use engine, owner checks, task queue, manual takeover, and saved time/step limits as Mobile Agent. It does not install software or accept licenses automatically.### Troubleshooting and logs@@ -75,7 +85,7 @@ Operational events are written to `mobile/mobile.log` relative to the active dat| `readuntil() called while another coroutine is already waiting` during startup | Older code let status polling read the driver’s initialization pipe concurrently. The fix shares `driver_lock` across initialization and commands and skips geometry polling during lifecycle transitions. Restart the backend after updating. || Phone works but an old error remains | Current UI clears recovered connection warnings; dismiss action errors. Refresh the frontend after updating. || New Android node is absent | Restart the backend to register the plugin and refresh the frontend. Search for **Android**, type `android_tool`. |-| Task asks for a model | Connect exactly one supported model to the phone node’s **Model** input and save the workflow. The parent agent’s model connection alone is insufficient. |+| Task asks for a model | Select a supported global model, choose a custom provider/model in the phone’s settings, or connect a model to the phone’s **Model** input. A parent agent’s separate custom model is not inherited automatically. || Live view cannot connect | Check recent video events. Only one viewer is supported; close another preview and use **Reconnect**. |`setup-status.json` retains setup progress across backend restarts. Recent diagnostic events in status are bounded to 40 records in memory; `mobile.log` and its rotated backups retain operational history on disk. Logs exclude user content, but still include workflow/run identifiers: review them before sharing. The startup race explains a failed request and phone cleanup; it does not by itself prove a whole-backend crash.diff --git a/server/nodes/mobile/_node.py b/server/nodes/mobile/_node.pyindex bfb9962e..51cb45a5 100644--- a/server/nodes/mobile/_node.py+++ b/server/nodes/mobile/_node.py@@ -3,7 +3,7 @@from datetime import timedeltaimport hashlibimport json-from typing import Any+from typing import Any, Literalfrom pydantic import BaseModel, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, NodeUserErrorfrom services.plugin.scaling import RetryPolicy, TaskQueue@@ -11,6 +11,17 @@ from services.plugin.scaling import RetryPolicy, TaskQueueclass MobileParams(BaseModel):prompt: str = Field(default="", max_length=20000, json_schema_extra={"rows": 4})+ model_source: Literal["global", "custom"] = Field(+ default="global", title="Model selection",+ description="Use the global model or choose one for this phone. A connected Model node always takes priority.",+ )+ provider: str = Field(+ default="openai", title="AI provider",+ json_schema_extra={"enum": ["openai", "anthropic", "gemini"], "displayOptions": {"show": {"model_source": ["custom"]}}},+ )+ model: str = Field(default="", title="Model", json_schema_extra={+ "placeholder": "Choose a model", "displayOptions": {"show": {"model_source": ["custom"]}},+ })max_steps: int = Field(default=40, ge=1, le=200)timeout_s: int = Field(default=900, ge=30, le=3600)@@ -49,7 +60,7 @@ async def require_mobile_owner(principal: str) -> None:raise NodeUserError("The shared mobile device is available to the installation owner only")-async def resolve_model(ctx: NodeContext) -> dict:+async def resolve_model(ctx: NodeContext, params: MobileParams | None = None) -> dict:from services.plugin.deps import get_ai_service, get_databasefrom services.llm.config import get_default_model_asyncfrom services.node_registry import get_node_class@@ -57,27 +68,41 @@ async def resolve_model(ctx: NodeContext) -> dict:from constants import detect_ai_providerconnections = [edge for edge in ctx.edges if edge.get("target") == ctx.node_id and edge_target_handle(edge) == "input-model"]- if len(connections) != 1:- raise NodeUserError("Connect exactly one AI model to this phone node's Model input")- source = next((node for node in ctx.nodes if node.get("id") == connections[0].get("source")), None)- cls = get_node_class(source.get("type", "")) if source else None- if cls is None or cls.component_kind != "model" or (source.get("data") or {}).get("disabled"):- raise NodeUserError("Connect an enabled AI model node to this phone node")- parameters = await get_database().get_node_parameters(source["id"]) or {}- provider_ref = detect_ai_provider(source["type"], parameters)+ if len(connections) > 1:+ raise NodeUserError("Connect exactly one AI model to this phone node's Model input, or remove connections to use the global model")+ database = get_database()+ if connections:+ source = next((node for node in ctx.nodes if node.get("id") == connections[0].get("source")), None)+ cls = get_node_class(source.get("type", "")) if source else None+ if cls is None or cls.component_kind != "model" or (source.get("data") or {}).get("disabled"):+ raise NodeUserError("Connect an enabled AI model node to this phone node")+ parameters = await database.get_node_parameters(source["id"]) or {}+ provider_ref = detect_ai_provider(source["type"], parameters)+ selected_model = parameters.get("model")+ else:+ config = params or MobileParams.model_validate(await database.get_node_parameters(ctx.node_id) or {})+ if config.model_source == "custom":+ provider_ref, selected_model = config.provider, config.model+ else:+ # The toolbar and Settings handlers persist the installation-wide+ # selection in the default settings row, separate from auth identity.+ settings = await database.get_user_settings("default") or {}+ provider_ref = settings.get("default_llm_provider")+ selected_model = settings.get("default_llm_model")+ if not provider_ref or not selected_model:+ raise NodeUserError("Choose a global AI model in the toolbar, select Custom in this phone's Model selection, or connect a Model node")adapters = {"openai": ("openai", "OPENAI_API_KEY"),"anthropic": ("anthropic", "ANTHROPIC_API_KEY"),"gemini": ("google", "GOOGLE_API_KEY"),}if provider_ref not in adapters:- raise NodeUserError("Mobile currently supports OpenAI, Anthropic, or Gemini model connectors")+ raise NodeUserError(f"The selected provider '{provider_ref}' is not supported by the phone engine. Choose an OpenAI, Anthropic, or Gemini model in the global selector or this phone's settings")auth = get_ai_service().authkey = await auth.get_api_key(provider_ref, "default")if not key:raise NodeUserError("Connect the selected model provider in Settings before running Mobile")- models = await auth.get_stored_models(provider_ref, "default")- model = parameters.get("model") or (models[0] if models else await get_default_model_async(provider_ref, get_database()))+ model = selected_model or await get_default_model_async(provider_ref, database)provider, variable = adapters[provider_ref]return {"provider": provider, "model": model, "model_env": {variable: key}}@@ -117,7 +142,7 @@ class MobileUseAgent(ActionNode):if not params.prompt.strip():raise NodeUserError("Enter a task for the mobile agent")runtime = get_runtime()- model = await resolve_model(ctx)+ model = await resolve_model(ctx, params)config = params.model_dump()directive = (ctx.raw.get("_raw_parameters") or {}).get("system_message")if directive and directive != config["prompt"]:diff --git a/server/tests/test_android_tool.py b/server/tests/test_android_tool.pyindex 9767b217..09c76184 100644--- a/server/tests/test_android_tool.py+++ b/server/tests/test_android_tool.py@@ -33,10 +33,14 @@ async def test_tool_uses_saved_limits_and_existing_mobile_pipeline(monkeypatch):result = await AndroidTool().execute_as_tool({"prompt": "Open Settings"}, {"max_steps": 7, "timeout_s": 60}, ctx)assert result.get("error") is None, resultargs = runtime.run.await_args.kwargs- assert args["params"] == {"prompt": "Open Settings", "max_steps": 7, "timeout_s": 60}+ assert args["params"]["prompt"] == "Open Settings"+ assert args["params"]["max_steps"] == 7+ assert args["params"]["timeout_s"] == 60assert args["node_id"] == "phone-tool"owner.assert_awaited_once_with("owner")- model.assert_awaited_once_with(ctx)+ model.assert_awaited_once()+ assert model.await_args.args[0] is ctx+ assert model.await_args.args[1].model_source == "global"def test_diagnostics_are_bounded_and_exclude_content(monkeypatch, tmp_path):diff --git a/server/tests/test_mobile_integration.py b/server/tests/test_mobile_integration.pyindex 02e7c9e8..53f65e8a 100644--- a/server/tests/test_mobile_integration.py+++ b/server/tests/test_mobile_integration.py@@ -38,9 +38,6 @@ async def test_connector_uses_saved_model_and_only_selected_key(monkeypatch):async def test_connector_requires_exactly_one_model():ctx = context()- ctx.edges = []- with pytest.raises(NodeUserError, match="exactly one"):- await _node.resolve_model(ctx)ctx.edges = [{"target": "mobile", "targetHandle": "input-model"}] * 2with pytest.raises(NodeUserError, match="exactly one"):await _node.resolve_model(ctx)diff --git a/server/tests/test_mobile_models.py b/server/tests/test_mobile_models.pynew file mode 100644index 00000000..c8d7e049--- /dev/null+++ b/server/tests/test_mobile_models.py@@ -0,0 +1,88 @@+"""Global/default/custom model precedence, without provider requests."""++from types import SimpleNamespace+from unittest.mock import AsyncMock+import pytest+from services.plugin import NodeContext, NodeUserError+from nodes.mobile._node import MobileParams, resolve_model+++def models(monkeypatch):+ import services.plugin.deps as deps+ import services.node_registry as registry+ import constants+ database = SimpleNamespace(+ get_node_parameters=AsyncMock(return_value={}),+ get_user_settings=AsyncMock(return_value={"default_llm_provider": "gemini", "default_llm_model": "global-vision"}),+ get_provider_defaults=AsyncMock(return_value={"default_model": "provider-default"}),+ )+ auth = SimpleNamespace(get_api_key=AsyncMock(return_value="selected-key"))+ monkeypatch.setattr(deps, "get_database", lambda: database)+ monkeypatch.setattr(deps, "get_ai_service", lambda: SimpleNamespace(auth=auth))+ monkeypatch.setattr(registry, "get_node_class", lambda _: SimpleNamespace(component_kind="model"))+ monkeypatch.setattr(constants, "detect_ai_provider", lambda *_: "anthropic")+ return database, auth+++def context():+ return NodeContext(node_id="phone", node_type="android_tool", workflow_id="wf", execution_id="run")+++async def test_global_selection_is_read_fresh_and_ignores_drag_defaults(models):+ db, auth = models+ params = MobileParams(provider="openrouter", model="old-drag-default")+ result = await resolve_model(context(), params)+ assert result == {"provider": "google", "model": "global-vision", "model_env": {"GOOGLE_API_KEY": "selected-key"}}+ db.get_user_settings.assert_awaited_once_with("default")+ auth.get_api_key.assert_awaited_once_with("gemini", "default")+ db.get_user_settings.return_value = {"default_llm_provider": "openai", "default_llm_model": "new-global"}+ assert (await resolve_model(context(), params))["model"] == "new-global"+++async def test_custom_selection_does_not_read_global(models):+ db, _ = models+ result = await resolve_model(context(), MobileParams(model_source="custom", provider="openai", model="custom-vision"))+ assert result["provider"] == "openai"+ assert result["model"] == "custom-vision"+ db.get_user_settings.assert_not_awaited()+++async def test_connected_model_overrides_global_and_custom(models):+ db, _ = models+ db.get_node_parameters.return_value = {"model": "connected-vision", "api_key": "do-not-use"}+ ctx = context()+ ctx.nodes = [{"id": "model", "type": "anthropicChatModel"}]+ ctx.edges = [{"source": "model", "target": "phone", "targetHandle": "input-model"}]+ result = await resolve_model(ctx, MobileParams(model_source="custom", provider="openai", model="custom"))+ assert result == {"provider": "anthropic", "model": "connected-vision", "model_env": {"ANTHROPIC_API_KEY": "selected-key"}}+ db.get_user_settings.assert_not_awaited()+++async def test_disabled_connector_does_not_silently_fallback(models):+ ctx = context()+ ctx.nodes = [{"id": "model", "type": "anthropicChatModel", "data": {"disabled": True}}]+ ctx.edges = [{"source": "model", "target": "phone", "targetHandle": "input-model"}]+ with pytest.raises(NodeUserError, match="enabled"):+ await resolve_model(ctx)++[email protected]("settings,match", [({}, "Choose a global"), ({"default_llm_provider": "ollama", "default_llm_model": "local"}, "not supported")])+async def test_missing_or_unsupported_global_is_actionable(models, settings, match):+ db, auth = models+ db.get_user_settings.return_value = settings+ with pytest.raises(NodeUserError, match=match):+ await resolve_model(context(), MobileParams())+ auth.get_api_key.assert_not_awaited()+++async def test_missing_key_is_actionable(models):+ _, auth = models+ auth.get_api_key.return_value = None+ with pytest.raises(NodeUserError, match="Settings"):+ await resolve_model(context(), MobileParams())+++async def test_blank_custom_model_uses_provider_default(models):+ result = await resolve_model(context(), MobileParams(model_source="custom", provider="openai"))+ assert result["model"] == "provider-default"