diff --git a/.env.example b/.env.example index 0fdc112f..111d3928 100644 --- a/.env.example +++ b/.env.example @@ -589,3 +589,8 @@ ENABLE_JAPANESE_CONTEXT_READING=false # BEGIN GENERATED CONFIG: desktop_extensions # Extension downloads # END GENERATED CONFIG: desktop_extensions + +# BEGIN GENERATED CONFIG: auip_interaction +# AI application interaction +# AUIP_INTERACTION_ENABLED=true +# END GENERATED CONFIG: auip_interaction diff --git a/config/catalog/general/application_interaction.json b/config/catalog/general/application_interaction.json new file mode 100644 index 00000000..b4c38c42 --- /dev/null +++ b/config/catalog/general/application_interaction.json @@ -0,0 +1,28 @@ +{ + "id": "auip_interaction", + "title": { + "en-US": "AI application interaction", + "zh-CN": "AI 应用交互" + }, + "description": { + "en-US": "Choose whether Amadeus joins AUIP applications from conversation. Creating, opening and manually using apps stays available.", + "zh-CN": "选择 Amadeus 是否从对话中参与 AUIP 应用。创建、打开和手动使用应用始终可用。" + }, + "desktop": true, + "apply": "host", + "config": { + "AUIP_INTERACTION_ENABLED": { + "type": "boolean", + "title": { + "en-US": "Let Amadeus interact with applications", + "zh-CN": "允许 Amadeus 与应用交互" + }, + "description": { + "en-US": "When off, chat stops evaluating AUIP and Amadeus starts no new application sessions. If applications are already open, they keep working and chat can still direct them until the last one ends; turning it back on cancels the pending shutdown. Saved across restarts.", + "zh-CN": "关闭后,聊天不再评估 AUIP,Amadeus 也不再启动新的应用会话。若已有应用在运行,它们可继续使用,聊天仍可操作,直到最后一个结束;重新开启会取消待关闭状态。跨重启保存。" + }, + "default": true, + "runtime_key": "auip_interaction_enabled" + } + } +} diff --git a/config/settings.py b/config/settings.py index e1fb1af5..cba55baf 100644 --- a/config/settings.py +++ b/config/settings.py @@ -27,6 +27,7 @@ _catalog_values = read_catalog_environment(_ENV) AMADEUS_CHARACTER_ID: str = _catalog_values["AMADEUS_CHARACTER_ID"] AMADEUS_MAIN_CHAT_CHARACTER_PROMPT_JA: str = _catalog_values["AMADEUS_MAIN_CHAT_CHARACTER_PROMPT_JA"] +AUIP_INTERACTION_ENABLED: bool = _catalog_values["AUIP_INTERACTION_ENABLED"] AUIP_ARTIFACT_STYLE_ENABLED: bool = _catalog_values["AUIP_ARTIFACT_STYLE_ENABLED"] VTS_ENABLED: bool = _catalog_values["VTS_ENABLED"] VTS_WS_URL: str = _catalog_values["VTS_WS_URL"] diff --git a/docs/auip_application_sessions.md b/docs/auip_application_sessions.md index 4019589f..d0c9b946 100644 --- a/docs/auip_application_sessions.md +++ b/docs/auip_application_sessions.md @@ -91,6 +91,43 @@ The role may interpret the user's intent or narrate a verified transition, but its prose is never proof that an action ran. Completion belongs to the Host-accepted receipt path. +## Turning AI application interaction off + +**Settings → Providers → AI application interaction** is one persisted, global +switch (`AUIP_INTERACTION_ENABLED`, default on). It applies to the running +backend immediately and is saved across restarts. It withdraws model +participation only; it is not the `AUIP_CONTROL_DECISION_ENABLED` control-path +selector, which chooses between the current and legacy proposal paths. + +Turning it off while no AppSession is active takes effect at once. With any +AppSession active, the switch is **pending off**: Main Chat keeps its usual AUIP +evaluation on every turn, and every session that was active can continue, so a +user can still direct a running game from chat. The Host starts no new AppSession +while shutdown is pending, including a launch requested earlier or deferred until +Work finishes. Admission enforces this: while the switch is off or pending off, +registration through any attach ticket and a self-attach request are refused +with `auip_interaction_disabled`, and the application stays standalone, as with +"Not now". When the last active AppSession ends, the switch takes effect. +Turning it back on during that period cancels the pending shutdown. + +Once it has taken effect: + +- ordinary chat makes no AUIP entry or control model call and receives no app + launch candidates or focused-app context, even when historical projects, + launchable apps or active Work exist; +- Amadeus takes no participant turns, issues no automatic or controller + actions, and adds no AUIP narration; requests to collaborate or delegate are + refused with `auip_interaction_disabled`, and so is a control decided before + the last session ended; +- creating apps through Work, opening them, and using them by hand remain + available, along with AppSession identity, permission checks and receipts. + An app opened this way stays standalone, and the Work page says so instead + of waiting for it to connect. To connect it, turn the switch back on and + reopen the app. + +Turning it back on restores entry, participation and narration for later turns +with no replay. + ## Disconnect and recovery behavior A lost application connection becomes a visible `disconnected` AppSession diff --git a/electron/src/renderer/components/SettingsPage.tsx b/electron/src/renderer/components/SettingsPage.tsx index c26e811a..db985c8e 100644 --- a/electron/src/renderer/components/SettingsPage.tsx +++ b/electron/src/renderer/components/SettingsPage.tsx @@ -1224,6 +1224,8 @@ export default function SettingsPage({ send, subscribe, connected, reconnectBack } } else if (targetSection === 'general') { anchor = targetId?.includes('visual') ? 'settings-vision' : targetId?.includes('translation') ? 'settings-language' : '' + } else if (targetSection === 'providers' && targetId === 'application_interaction') { + anchor = 'settings-auip-interaction' } if (anchor) window.setTimeout(() => document.getElementById(anchor)?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 0) }, [openCharacters, setSection]) @@ -1579,6 +1581,9 @@ export default function SettingsPage({ send, subscribe, connected, reconnectBack {(Array.isArray(config.acp_credentials) ? config.acp_credentials as StartupField[] : []).map(field => )} +
group.id === 'auip_interaction')!.title['en-US']} detail={catalogGroups.find(group => group.id === 'auip_interaction')!.description['en-US']}> + {renderRuntimeGroup('auip_interaction', 'CommandPrompt')} +
{artifactConfiguration.map(group => )} diff --git a/electron/src/renderer/components/WorkPage.tsx b/electron/src/renderer/components/WorkPage.tsx index bb3450ad..f48265f3 100644 --- a/electron/src/renderer/components/WorkPage.tsx +++ b/electron/src/renderer/components/WorkPage.tsx @@ -556,18 +556,25 @@ export default function WorkPage({ send, subscribe, connected }: WorkPageProps) if (!launchUrl) throw new Error('The host did not return an AUIP launch descriptor.') if (!artifactRef) throw new Error('The host did not bind the AUIP launch to an artifact.') if (!hostSurfaceId) throw new Error('The host did not bind an AUIP surface identity.') - setAuipExperience({ - artifactRef, - title: 'AUIP application', - status: 'connecting', - }) + // With AI application interaction off, the Host refuses the registration, + // so the app opens on its own and no connection will follow. + const standalone = prepared.auip_interaction_enabled === false + if (!standalone) { + setAuipExperience({ + artifactRef, + title: 'AUIP application', + status: 'connecting', + }) + } const opened = await window.amadeus?.openAuipApp(launchUrl, hostSurfaceId, workItemId) if (!opened?.ok) { throw new Error(opened?.detail || 'The desktop host refused the AUIP launch URL.') } setAuipLaunchFeedback({ status: 'success', - message: 'Application opened. Its one-time Attach ticket is waiting for registration.', + message: standalone + ? 'AI application interaction is off, so the application opened on its own. Turn it on in Settings → Providers to let Amadeus join.' + : 'Application opened. Its one-time Attach ticket is waiting for registration.', }) } catch (error) { setAuipExperience(undefined) @@ -721,6 +728,13 @@ export default function WorkPage({ send, subscribe, connected }: WorkPageProps) return () => unsubscribe() }, [applyWorkEnvelope, subscribe]) + // A refused host control, e.g. auip_interaction_disabled, changes no + // AppSession state, so no auip.updated arrives to explain it. + const showAuipRefusal = useCallback((result: Record) => { + if (result.ok !== false) return + setAuipExperience(previous => previous && { ...previous, operatorError: String(result.error || 'auip_request_refused') }) + }, []) + useEffect(() => { const unsubscribe = subscribe('auip.updated', payload => { setAuipExperience(previous => { @@ -1327,14 +1341,14 @@ export default function WorkPage({ send, subscribe, connected }: WorkPageProps) void send('auip.mode.set', { app_session_id: auipExperience.appSessionId, mode, - }) + }).then(showAuipRefusal) }} onStep={() => { if (!auipExperience.appSessionId) return void send('auip.step', { app_session_id: auipExperience.appSessionId, instruction: 'Take one appropriate declared action now.', - }) + }).then(showAuipRefusal) }} onLeave={() => { if (!auipExperience.appSessionId) return diff --git a/electron/src/renderer/components/sceneCapabilityProjection.ts b/electron/src/renderer/components/sceneCapabilityProjection.ts index 12ec3e0d..474c189b 100644 --- a/electron/src/renderer/components/sceneCapabilityProjection.ts +++ b/electron/src/renderer/components/sceneCapabilityProjection.ts @@ -657,17 +657,21 @@ export function buildCapabilityProfiles( const modelRoles = groups(settings.model_roles) const auipAction = findGroup(modelRoles, 'auip_action') const auipReady = groupAvailable(auipAction) + // The user's switch outranks role readiness: off is a choice, not a fault. + const auipTurnedOff = backendFactsAvailable && settings.auip_interaction_enabled === false const auipItem: SceneCapabilityItem = { id: 'application_interaction', label: 'Application interaction', implementation: 'Host AUIP runtime · action role', - detail: groupDetail(auipAction, 'The Host owns AUIP session identity, action legality, receipts, and application attachment.'), + detail: auipTurnedOff + ? 'AI application interaction is turned off. Apps can still be created, opened and used manually.' + : groupDetail(auipAction, 'The Host owns AUIP session identity, action legality, receipts, and application attachment.'), importance: 'optional', - state: !backendFactsAvailable ? 'unknown' : auipReady ? 'ready' : 'attention', - stateLabel: !backendFactsAvailable ? 'Backend not connected' : auipReady ? 'Available' : 'Action role needs setup', + state: !backendFactsAvailable ? 'unknown' : auipTurnedOff ? 'inactive' : auipReady ? 'ready' : 'attention', + stateLabel: !backendFactsAvailable ? 'Backend not connected' : auipTurnedOff ? 'Turned off' : auipReady ? 'Available' : 'Action role needs setup', policyLabel: 'Shared conversation capability', - currentLabel: auipAction?.active ? 'B2 action role active' : 'Observe or legacy mode', - configureSection: 'models', + currentLabel: auipTurnedOff ? 'Off' : auipAction?.active ? 'B2 action role active' : 'Observe or legacy mode', + configureSection: auipTurnedOff ? 'providers' : 'models', } const applicationInteraction: CapabilityProfile = { id: 'application_interaction', diff --git a/electron/src/renderer/locales/zh-CN.json b/electron/src/renderer/locales/zh-CN.json index 545242ad..59efe422 100644 --- a/electron/src/renderer/locales/zh-CN.json +++ b/electron/src/renderer/locales/zh-CN.json @@ -8,6 +8,7 @@ "ACP v1 preset using a referenced DeepSeek credential.": "使用所引用 DeepSeek 凭据的 ACP v1 预设。", "ACTIVE": "活动", "ACTIVE SESSION": "活动会话", + "AI application interaction is turned off. Apps can still be created, opened and used manually.": "AI 应用交互已关闭。应用仍可创建、打开并手动使用。", "AMADEUS AI WORK INTERFACE": "AMADEUS AI 工作界面", "AUIP ASSEMBLING": "正在组装 AUIP", "AUIP ATTACHING": "正在附加 AUIP", @@ -1271,6 +1272,7 @@ "Turn Timeline / Work Plan": "轮次时间线 / 工作计划", "Turn off automatic approval": "关闭自动审批", "Turn this on in Companion settings.": "请在陪玩设置中开启此功能。", + "Turned off": "已关闭", "Type a message or press mic to speak...": "输入消息,或按麦克风开始说话…", "Type a message to start.": "输入消息开始对话。", "Typed and spoken questions include a fresh game image. Notes and pins remain text-only.": "文字或语音提问会附上当时的新画面,笔记和标记仅保存文字。", diff --git a/electron/src/shared/configCatalog.generated.ts b/electron/src/shared/configCatalog.generated.ts index 4aaeb76d..eefcd8e6 100644 --- a/electron/src/shared/configCatalog.generated.ts +++ b/electron/src/shared/configCatalog.generated.ts @@ -198,6 +198,34 @@ export const catalogGroups: CatalogGroup[] = [ } } }, + { + "id": "auip_interaction", + "title": { + "en-US": "AI application interaction", + "zh-CN": "AI 应用交互" + }, + "description": { + "en-US": "Choose whether Amadeus joins AUIP applications from conversation. Creating, opening and manually using apps stays available.", + "zh-CN": "选择 Amadeus 是否从对话中参与 AUIP 应用。创建、打开和手动使用应用始终可用。" + }, + "desktop": true, + "apply": "host", + "config": { + "AUIP_INTERACTION_ENABLED": { + "type": "boolean", + "title": { + "en-US": "Let Amadeus interact with applications", + "zh-CN": "允许 Amadeus 与应用交互" + }, + "description": { + "en-US": "When off, chat stops evaluating AUIP and Amadeus starts no new application sessions. If applications are already open, they keep working and chat can still direct them until the last one ends; turning it back on cancels the pending shutdown. Saved across restarts.", + "zh-CN": "关闭后,聊天不再评估 AUIP,Amadeus 也不再启动新的应用会话。若已有应用在运行,它们可继续使用,聊天仍可操作,直到最后一个结束;重新开启会取消待关闭状态。跨重启保存。" + }, + "default": true, + "runtime_key": "auip_interaction_enabled" + } + } + }, { "id": "auip_artifact_style", "title": { diff --git a/electron/tests/auipInteractionSettings.test.mjs b/electron/tests/auipInteractionSettings.test.mjs new file mode 100644 index 00000000..dfcce865 --- /dev/null +++ b/electron/tests/auipInteractionSettings.test.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import test from 'node:test' +import { loadTypeScript } from './helpers/loadTypeScript.mjs' + +const key = 'AUIP_INTERACTION_ENABLED' + +test('AI application interaction defaults on and is a live, desktop-persisted setting', () => { + const { catalogApplication, desktopCatalogFields, runtimeCatalogFields } = loadTypeScript(new URL('../src/shared/configCatalog.ts', import.meta.url)) + assert.equal(desktopCatalogFields[key]?.default, true) + assert.equal(runtimeCatalogFields.auip_interaction_enabled?.key, key) + assert.equal(catalogApplication(key), 'host') +}) + +test('the AI application interaction choice survives desktop settings reloads', t => { + const { DesktopSettingsStore } = loadTypeScript(new URL('../src/main/desktopSettings.ts', import.meta.url), { + electron: { safeStorage: { isEncryptionAvailable: () => false } }, + }) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'amadeus-auip-interaction-')) + t.after(() => fs.rmSync(directory, { recursive: true, force: true })) + const open = () => new DesktopSettingsStore(path.join(directory, 'settings.json'), path.join(directory, '.env')) + assert.equal(open().backendEnvironment({})[key], undefined) + for (const value of [false, true]) { + open().update({}, { values: { [key]: value } }) + assert.equal(open().backendEnvironment({})[key], String(value)) + } + assert.throws(() => open().update({}, { values: { [key]: 'sometimes' } })) +}) diff --git a/electron/tests/i18nCatalog.test.mjs b/electron/tests/i18nCatalog.test.mjs index 05fdfe9f..6bb6a405 100644 --- a/electron/tests/i18nCatalog.test.mjs +++ b/electron/tests/i18nCatalog.test.mjs @@ -93,7 +93,7 @@ test('capability projection text has a translated entry in every configuration', snapshots.push({ llm_provider: llm, wake_enabled: voice, aec_realtime_enabled: voice, aec_realtime_barge_in: voice, wallpaper_caption_mode: caption, chat_translation_subtitles_enabled: voice, - vision_enabled: enabled, vision_mode: mode, vision_scope: scope, + vision_enabled: enabled, vision_mode: mode, vision_scope: scope, auip_interaction_enabled: voice, model_connections: ['deepseek', 'openai', 'gemini', 'bedrock', 'local', 'hybrid_local'].map(id => group(id, configured)), voice_configuration: [ group('speech_synthesis', configured, { TTS_BACKEND: voice ? 'gpt_sovits' : 'fish_audio' }, { active: true }), diff --git a/electron/tests/sceneCapabilityProjection.test.mjs b/electron/tests/sceneCapabilityProjection.test.mjs index 5353dff7..88d27b4e 100644 --- a/electron/tests/sceneCapabilityProjection.test.mjs +++ b/electron/tests/sceneCapabilityProjection.test.mjs @@ -246,3 +246,21 @@ test('Work readiness remains unknown without backend facts regardless of a store assert.equal(capabilities.find(item => item.id === 'work_execution').state, 'unknown') } }) + +test('turning AI application interaction off reads as a choice that points to its switch', () => { + const snapshot = configuredSnapshot() + snapshot.model_roles = [group('auip_action', true, {}, { active: true, status_ok: true })] + const availability = [{ provider_id: 'pi', configured: true, ready: true, registered: true, reason: 'ready' }] + const find = settings => exports.buildCapabilityProfiles(settings, availability) + .find(item => item.id === 'application_interaction') + const on = find({ ...snapshot, auip_interaction_enabled: true }) + assert.equal(on.state, 'ready') + assert.equal(on.configureSection, 'models') + const off = find({ ...snapshot, auip_interaction_enabled: false }) + assert.equal(off.state, 'inactive') + assert.equal(off.stateLabel, 'Turned off') + assert.equal(off.configureSection, 'providers') + assert.match(off.scenes.find(scene => scene.sceneId === 'chat').detail, /used manually/) + // An older backend that does not report the switch keeps the previous projection. + assert.equal(find(snapshot).state, 'ready') +}) diff --git a/server/auip_engagement.py b/server/auip_engagement.py index 56b308db..471924db 100644 --- a/server/auip_engagement.py +++ b/server/auip_engagement.py @@ -27,7 +27,11 @@ AuipParticipantProposal, ControllerCallable, ) -from server.auip_runtime import PENDING_ACTION_TIMEOUT_S, AuipRuntime, runtime +from server.auip_runtime import ( + PENDING_ACTION_TIMEOUT_S, + AuipRuntime, + runtime, +) from server.event_bus import bus from server.protocol import Method @@ -100,6 +104,11 @@ def set_b2_coordinator( async def set_mode(self, *, app_session_id: str, mode: str) -> dict[str, Any]: clean_requested = str(mode or "").strip().lower() + if ( + clean_requested in {"collaborate", "delegate"} + and not self.runtime.ai_interaction_in_effect() + ): + raise AuipProtocolError("auip_interaction_disabled") if clean_requested == "delegate" and ( self.controller is None or self.role_authorizer is None ): @@ -129,6 +138,8 @@ def request_step( expected_revision: int | None = None, current_role_response: str = "", ) -> dict[str, Any]: + if not self.runtime.ai_interaction_in_effect(): + raise AuipProtocolError("auip_interaction_disabled") if str(reason or "") == "explicit_step": self._cancel_deferred_automatic(app_session_id) b2_unavailable = bool( @@ -220,6 +231,9 @@ async def on_update(self, _method: str, payload: dict[str, Any]) -> None: self._remember_receipt(receipt_key) if app_session_id and str(payload.get("status") or "") != "active": self._cancel_receipt_watch(app_session_id) + if not self.runtime.ai_interaction_in_effect(): + # Receipt bookkeeping above stays truthful; no new turn is offered. + return event = payload.get("event") if isinstance(payload.get("event"), dict) else None if event is None: return diff --git a/server/auip_launch.py b/server/auip_launch.py index 1384efef..860ebabd 100644 --- a/server/auip_launch.py +++ b/server/auip_launch.py @@ -41,6 +41,7 @@ list_current_runnable_artifacts, ) from server.auip_contract import available_engagement_modes +from server.auip_runtime import ai_interaction_enabled from server.event_bus import bus from server.protocol import Method from server.work_permission_service import WorkPermissionService @@ -443,6 +444,13 @@ async def route_control( prepare_work: PreparationDispatcher | None = None, source_app_session_id: str = "", ) -> dict[str, Any]: + if ( + str(attrs.get("action") or "").strip().lower() != "prepare" + and not ai_interaction_enabled() + ): + # No new AUIP session while the switch is off or pending off, + # including a continuation deferred until Work finishes. + return {"ok": False, "error": "auip_interaction_disabled"} frozen = attrs.get("_host_launch_candidates") if frozen is not None: # Only Host candidate objects can cross this seam. Model JSON @@ -1138,7 +1146,8 @@ def authorize_prepare( ) -> bool: request = self._launch_requests.get(str(request_id or "")) return bool( - request is not None + ai_interaction_enabled() + and request is not None and request.session_id == str(session_id or "") and request.artifact_id == str(artifact_id or "") ) @@ -1317,6 +1326,11 @@ async def _emit_launch( candidate: AuipLaunchCandidate, mode: str, ) -> dict[str, Any]: + if not ai_interaction_enabled(): + # Reached by selections, deferred Work results and Attention cards + # that were created before the switch was turned off. + await self._announce_failure(session_id, "auip_interaction_disabled") + return {"ok": False, "error": "auip_interaction_disabled"} if candidate.project_id: try: self.work_roster.destination.available_project(candidate.project_id) diff --git a/server/auip_narration.py b/server/auip_narration.py index 590c856f..5fd6cd67 100644 --- a/server/auip_narration.py +++ b/server/auip_narration.py @@ -204,6 +204,9 @@ async def enqueue_update( facts are narrated in source order. """ + if not self.runtime.ai_interaction_in_effect(): + # Commentary is AI participation; accepted facts stay in the runtime. + return event = payload.get("event") if isinstance(payload.get("event"), dict) else {} app_session_id = str(payload.get("app_session_id") or "").strip() controller = ( diff --git a/server/auip_runtime.py b/server/auip_runtime.py index 1262cc39..4f002865 100644 --- a/server/auip_runtime.py +++ b/server/auip_runtime.py @@ -46,6 +46,17 @@ OPERATOR_STATUSES = frozenset({"idle", "thinking", "awaiting_receipt", "error"}) +def ai_interaction_enabled() -> bool: + """Read the user's live AI application interaction choice. + + This is the choice itself. While it is off, no AppSession may be + admitted, but sessions already active keep running until the last one + ends (see ``AuipRuntime.ai_interaction_in_effect``). + """ + + return bool(getattr(settings, "AUIP_INTERACTION_ENABLED", True)) + + @dataclass(frozen=True, slots=True) class _ContextProjectionLine: """One keyed role-context fact before budget packing.""" @@ -288,11 +299,17 @@ def register_attached( binding = self._attach_tickets.pop(clean_ticket, None) if binding is None: raise AuipProtocolError("invalid_attach_ticket") + if not ai_interaction_enabled(): + # Admission is the one place a session becomes active, so + # refusing here keeps pending off from ever gaining sessions. + # The app stays standalone and usable by hand. + raise AuipProtocolError("auip_interaction_disabled") + mode = binding.engagement_mode return self._register_parsed( parsed, conversation_id=binding.conversation_id, artifact_ref=binding.artifact_ref, - initial_engagement_mode=binding.engagement_mode, + initial_engagement_mode=mode, host_surface_id=binding.host_surface_id, ) @@ -1123,6 +1140,24 @@ def focus(self, *, conversation_id: str, app_session_id: str) -> dict[str, Any]: session.updated_at = time.time() return {"ok": True, **session.public_snapshot()} + def has_active_session(self) -> bool: + """Report whether any AppSession can still accept participation.""" + + with self._lock: + return any( + session.status == "active" for session in self._sessions.values() + ) + + def ai_interaction_in_effect(self) -> bool: + """Say whether AUIP evaluation and participation still run. + + Turning the switch off while AppSessions are active is *pending off*: + evaluation and participation continue for those sessions and end with + the last one. With none active, off takes effect immediately. + """ + + return ai_interaction_enabled() or self.has_active_session() + def get(self, app_session_id: str) -> dict[str, Any]: with self._lock: session = self._session(app_session_id) diff --git a/server/auip_self_attach.py b/server/auip_self_attach.py index 637cc3fa..09eeb327 100644 --- a/server/auip_self_attach.py +++ b/server/auip_self_attach.py @@ -25,7 +25,7 @@ ) from server.auip_app_source import ArtifactSource, discover_exported_auip_apps from server.auip_contract import AuipProtocolError, parse_manifest -from server.auip_runtime import AuipRuntime +from server.auip_runtime import AuipRuntime, ai_interaction_enabled SELF_ATTACH_TIMEOUT_S = 5 * 60.0 @@ -57,6 +57,9 @@ async def request( instance_id: str, entry_url: str, ) -> dict[str, Any]: + if not ai_interaction_enabled(): + # Offer no play options; the app stays standalone, as with "Not now". + raise AuipProtocolError("auip_interaction_disabled") parsed = parse_manifest(manifest) clean_instance = str(instance_id or "").strip() if not _INSTANCE_ID.fullmatch(clean_instance): diff --git a/server/cooperative_chat_ingress.py b/server/cooperative_chat_ingress.py index 2394f910..55f464f5 100644 --- a/server/cooperative_chat_ingress.py +++ b/server/cooperative_chat_ingress.py @@ -86,6 +86,7 @@ auip_decision_preserves_main_context, render_auip_role_grounding, ) +from server.auip_runtime import runtime as auip_app_runtime from server.interaction_branch import ( InteractionBranchRoutingLease, InteractionBranchRunStopUnconfirmed, @@ -1521,7 +1522,7 @@ def configure_auip(self, decider, router: Callable, *, def prefetch_auip_entry_context(self, session_id: str): """Prepare presentation during speech; never create a session or an action.""" context = self.auip_entry_context - if not session_id or context is None: + if not session_id or context is None or not auip_app_runtime.ai_interaction_in_effect(): return None async def prepare(): @@ -1654,7 +1655,10 @@ async def handle_auip_action(self, ingress, turn_id: str, text: str, admission, require_live_turn: Callable) -> dict | None: """Route focused control; schedule every inactive entry behind the role.""" - if self.auip_decider is None or self.auip_router is None: + if (self.auip_decider is None or self.auip_router is None + or not auip_app_runtime.ai_interaction_in_effect()): + # Off with no active app: no AUIP decision query and no entry + # prompt. While shutdown is pending, evaluation still runs. return None binding = ingress.loop._binding history = ingress.loop.prior_messages(turn_id) @@ -2026,22 +2030,27 @@ async def _apply_focused_auip(self, ingress, turn_id, text, admission, action = str(getattr(decision, "action", "") or "") read_facets = tuple(getattr(decision, "read_facets", ()) or ()) app_session_id = str(getattr(decision, "app_session_id", "") or "") + # A decision frozen before the last app session ended is refused here, + # before a step model call, read or app action can start. + disabled = not auip_app_runtime.ai_interaction_in_effect() + accepted_decision = getattr(decision, "status", "") == "ok" and not disabled confirmed = require_live_turn() if inspect.isawaitable(confirmed): admission = await confirmed if not independent: ingress.loop._effects.accept_no_effect(admission, - reason="auip_rejected" if getattr(decision, "status", "") != "ok" + reason="auip_rejected" if not accepted_decision else "auip_read" if read_facets else "auip_" + action) record_user() display_text = None role_scope = ({"role_scope":"この応答ではアプリ側の要求だけを扱います。独立したWorkは別の担当が説明します。"} if independent else {}) - if getattr(decision, "status", "") != "ok": + if not accepted_decision: receipt = {"state":"auip_rejected", "action":action, "input_id":admission.utterance_id, "app_session_id":app_session_id, "outcome":{"ok":False, - "reason":str(getattr(decision, "reason", "") or "app_control_unavailable"), + "reason":"auip_interaction_disabled" if disabled else + str(getattr(decision, "reason", "") or "app_control_unavailable"), "available_modes":list(getattr(decision, "available_modes", ()) or ())}} return await finish(receipt, {"source":"host_receipt", **receipt, **role_scope}) step_request = self.auip_step @@ -2264,6 +2273,9 @@ def role_app_context_for_session( """Use the shared role projections independently of action proposals.""" from server.auip_runtime import runtime + if not runtime.ai_interaction_in_effect(): + # The app stays usable by hand, but its state is not chat context. + return "" expected = str(app_session_id or "").strip() # Rendering is synchronous and the Runtime uses an RLock. Keep the # identity check and both existing projections in one focus snapshot, diff --git a/server/handlers/auip_handler.py b/server/handlers/auip_handler.py index 0c0d14d4..027576ae 100644 --- a/server/handlers/auip_handler.py +++ b/server/handlers/auip_handler.py @@ -23,7 +23,7 @@ reconcile_active_auip_control, ) from server.auip_engagement import AuipEngagementCoordinator -from server.auip_runtime import AuipRuntime, runtime +from server.auip_runtime import AuipRuntime, ai_interaction_enabled, runtime from server.event_bus import bus from server.protocol import Method from server.ws_handler import RequestHandler @@ -138,6 +138,10 @@ async def handle(self, method: str, params: dict[str, Any]) -> dict[str, Any] | **ticket, "host_surface_id": host_surface_id, "launch_url": launch_url, + # While the switch is off the app still opens, but its + # registration will be refused, so no caller should wait + # for it to connect. + "auip_interaction_enabled": ai_interaction_enabled(), } if method == Method.AUIP_LAUNCH_RESULT: if self.launch is None: @@ -310,6 +314,11 @@ async def route_control( performs no wording match and accepts no model-supplied AppSession id. """ + if not self.runtime.ai_interaction_in_effect(): + # A decision captured before the last session ended may still + # arrive; it is refused here, before any app or launch side + # effect, and presented through the ordinary rejection receipt. + return {"ok": False, "error": "auip_interaction_disabled"} projection = self.runtime.focused_projection(session_id) control = reconcile_active_auip_control(attrs, projection) action = str(control.get("action") or "").strip().lower() diff --git a/server/handlers/system_handler.py b/server/handlers/system_handler.py index abde2ca4..b16a761e 100644 --- a/server/handlers/system_handler.py +++ b/server/handlers/system_handler.py @@ -721,6 +721,7 @@ async def _get_config(self, params: dict[str, Any]) -> dict[str, Any]: "model_roles": _model_role_configuration(settings), "work_provider_configuration": _work_provider_configuration(settings), "work_permission_auto_approve": settings.WORK_PERMISSION_AUTO_APPROVE, + "auip_interaction_enabled": settings.AUIP_INTERACTION_ENABLED, "graphics": { "profile": settings.GRAPHICS_PROFILE, "custom_max_fps": settings.RENDER_MAX_FPS, @@ -854,6 +855,9 @@ async def _set_config(self, params: dict[str, Any]) -> dict[str, Any]: if "work_permission_auto_approve" in values: settings.WORK_PERMISSION_AUTO_APPROVE = values["work_permission_auto_approve"] updated.append("work_permission_auto_approve") + if "auip_interaction_enabled" in values: + settings.AUIP_INTERACTION_ENABLED = values["auip_interaction_enabled"] + updated.append("auip_interaction_enabled") if CHARACTER_PROMPT_SETTING in values: updated.extend(set_character_prompt(values[CHARACTER_PROMPT_SETTING])) if "asr_backend" in values: diff --git a/tests/test_auip_handler.py b/tests/test_auip_handler.py index 39e46ca9..939785b3 100644 --- a/tests/test_auip_handler.py +++ b/tests/test_auip_handler.py @@ -9,6 +9,7 @@ from types import SimpleNamespace from typing import Any +from config import settings from server.auip_app_connection import ( APP_METHODS, AuipAppConnectionManager, @@ -192,6 +193,29 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_prepare_says_when_the_app_will_stay_standalone(monkeypatch) -> None: + async def prepare() -> dict: + with tempfile.TemporaryDirectory() as tmp: + host = AuipHandler( + AuipRuntime(), + artifacts=_Store(Path(tmp)), + current_session_id=lambda: "host-session", + ) + return await host.handle( + Method.AUIP_ATTACH_PREPARE, {"artifact_id": "artifact-1"} + ) + + assert asyncio.run(prepare())["auip_interaction_enabled"] is True + + monkeypatch.setattr(settings, "AUIP_INTERACTION_ENABLED", False) + off = asyncio.run(prepare()) + # The app still opens through the usual descriptor; only its registration + # is refused, so the caller must not wait for a connection. + assert off["ok"] is True + assert parse_app_launch_url(off["launch_url"])["attachTicket"] == off["attach_ticket"] + assert off["auip_interaction_enabled"] is False + + def test_preview_handoff_failure_does_not_weaken_validated_auip_prepare() -> None: async def scenario() -> None: runtime = AuipRuntime() diff --git a/tests/test_auip_interaction_switch.py b/tests/test_auip_interaction_switch.py new file mode 100644 index 00000000..8686f7a6 --- /dev/null +++ b/tests/test_auip_interaction_switch.py @@ -0,0 +1,520 @@ +"""The user's AI application interaction switch withdraws only model participation.""" + +from __future__ import annotations + +import asyncio +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from config import settings +from server.auip_contract import AUIP_SCHEMA, AuipProtocolError +from server.auip_engagement import AuipEngagementCoordinator +from server.auip_launch import AuipLaunchCandidate, AuipLaunchCoordinator +from server.auip_narration import AuipNarrationAdapter, AuipNarrationProfile +from server.auip_runtime import AuipRuntime +from server.auip_self_attach import AuipSelfAttachCoordinator +from server.handlers.auip_handler import AuipHandler +from server.handlers.system_handler import SystemHandler +from server.protocol import Method + + +def _approve(_context: dict) -> dict: + return {"decision": "approve", "reason": "test policy"} + + +def _manifest(*, stances: tuple[str, ...] = ("spectator", "participant")) -> dict: + return { + "schema": AUIP_SCHEMA, + "app": {"id": "turn-game", "title": "Turn Game", "version": "0.1.0"}, + "events": { + "game.turn_ready": {"participantOpportunity": True}, + "game.move_committed": {"beat": True}, + }, + "actions": { + "game.move": { + "description": "Make one legal move.", + "risk": "local_execution", + } + }, + "stances": list(stances), + } + + +def _controller_manifest() -> dict: + manifest = _manifest() + manifest["actions"]["game.set_policy"] = { + "description": "Set the exact automatic play policy.", + "risk": "local_execution", + "inputSchema": { + "type": "object", + "properties": {"style": {"type": "string"}}, + "required": ["style"], + "additionalProperties": False, + }, + } + manifest["situationKinds"] = ["controller/v1"] + manifest["controller"] = { + "policyActions": ["game.set_policy"], + "leaseDurationMs": 30_000, + "maxActionRateHz": 10, + "takeover": "immediate", + } + return manifest + + +def _controller_state(status: str, policy_revision: object = None) -> dict: + return { + "controller": { + "kind": "controller/v1", + "status": status, + "policyRevision": policy_revision, + "policyAction": "game.set_policy" if policy_revision else None, + "policySummary": "Play defensively" if policy_revision else "", + } + } + + +def _registered(runtime: AuipRuntime, manifest: dict, conversation: str) -> dict: + registered = runtime.register(manifest=manifest, conversation_id=conversation) + runtime.publish_state( + app_session_id=registered["app_session_id"], + bridge_token=registered["bridge_token"], + revision=1, + state={"turn": "kurisu"}, + ) + return registered + + +def _turn_ready(runtime: AuipRuntime, registered: dict, event_id: str) -> dict: + return runtime.publish_event( + app_session_id=registered["app_session_id"], + bridge_token=registered["bridge_token"], + event_id=event_id, + type="game.turn_ready", + actor="app", + revision=1, + payload={}, + ) + + +def _off(monkeypatch) -> None: + monkeypatch.setattr(settings, "AUIP_INTERACTION_ENABLED", False) + + +def _on(monkeypatch) -> None: + monkeypatch.setattr(settings, "AUIP_INTERACTION_ENABLED", True) + + +def _launch_coordinator() -> tuple[AuipLaunchCoordinator, AsyncMock]: + emit = AsyncMock() + coordinator = AuipLaunchCoordinator( + artifacts=MagicMock(), + work_roster=MagicMock(), + attention=MagicMock(), + emit=emit, + ) + coordinator._announce_failure = AsyncMock() + return coordinator, emit + + +def test_off_with_no_active_session_takes_effect_at_once_and_on_restores( + monkeypatch, +) -> None: + runtime = AuipRuntime() + assert runtime.ai_interaction_in_effect() is True + _off(monkeypatch) + assert runtime.ai_interaction_in_effect() is False + _on(monkeypatch) + assert runtime.ai_interaction_in_effect() is True + + # A session that is no longer active does not hold shutdown open. + registered = _registered(runtime, _manifest(), "ended") + runtime.disconnect(registered["app_session_id"]) + _off(monkeypatch) + assert runtime.ai_interaction_in_effect() is False + + +def test_pending_off_keeps_both_sessions_usable_until_the_last_one_ends( + monkeypatch, +) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + first = _registered(runtime, _manifest(), "pending") + second = _registered(runtime, _manifest(), "pending") + calls: list[dict] = [] + + async def controller(context: dict) -> dict: + calls.append(context) + return {"action": "wait", "reason": "observed"} + + engagement = AuipEngagementCoordinator( + app_runtime=runtime, + controller=controller, + role_authorizer=_approve, + ) + host = AuipHandler( + runtime, + current_session_id=lambda: "pending", + engagement=engagement, + ) + for registered in (first, second): + runtime.set_engagement_mode( + app_session_id=registered["app_session_id"], mode="collaborate" + ) + + _off(monkeypatch) + # Pending off: chat evaluation and both sessions keep working. + assert runtime.ai_interaction_in_effect() is True + for number, registered in enumerate((first, second)): + await engagement.on_update( + Method.AUIP_UPDATED, + _turn_ready(runtime, registered, f"pending-turn-{number}"), + ) + await engagement.wait_for_idle(registered["app_session_id"]) + assert len(calls) == 2 + runtime.focus( + conversation_id="pending", app_session_id=second["app_session_id"] + ) + routed = await host.route_control( + {"action": "observe", "_host_app_session_id": second["app_session_id"]}, + session_id="pending", + user_text="見ていて", + turn_id="pending-control", + ) + assert routed["engagement_mode"] == "observe" + + # Ending the first leaves evaluation running; ending the second stops it. + runtime.disconnect(first["app_session_id"]) + assert runtime.ai_interaction_in_effect() is True + runtime.disconnect(second["app_session_id"]) + assert runtime.ai_interaction_in_effect() is False + await engagement.close() + + asyncio.run(scenario()) + + +def test_pending_off_refuses_a_third_session_and_deferred_launches(monkeypatch) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + _registered(runtime, _manifest(), "third") + _registered(runtime, _manifest(), "third") + coordinator, emit = _launch_coordinator() + candidate = MagicMock(spec=AuipLaunchCandidate) + + _off(monkeypatch) + assert runtime.ai_interaction_in_effect() is True + for attrs in ( + {"action": "launch", "target": "Turn Game", "mode": "collaborate"}, + {"action": "launch", "target": "delivery", "after": "work"}, + {"action": "launch", "_host_launch_candidates": (candidate,)}, + ): + routed = await coordinator.route_control( + attrs, session_id="third", turn_id="third-turn" + ) + assert routed == {"ok": False, "error": "auip_interaction_disabled"} + assert coordinator._deferred == {} + + # A selection, Attention card or deferred Work result created earlier. + refused = await coordinator._emit_launch("third", candidate, "observe") + assert refused == {"ok": False, "error": "auip_interaction_disabled"} + assert emit.await_count == 0 + + # An earlier launch request cannot mint an attach ticket either. + coordinator._launch_requests["earlier"] = MagicMock( + session_id="third", artifact_id="artifact-1" + ) + assert not coordinator.authorize_prepare( + session_id="third", request_id="earlier", artifact_id="artifact-1" + ) + _on(monkeypatch) + assert coordinator.authorize_prepare( + session_id="third", request_id="earlier", artifact_id="artifact-1" + ) + + asyncio.run(scenario()) + + +def test_switching_back_on_cancels_pending_shutdown(monkeypatch) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + registered = _registered(runtime, _manifest(), "cancel") + coordinator, _emit = _launch_coordinator() + coordinator.candidates = lambda _session_id: [] + + _off(monkeypatch) + refused = await coordinator.route_control( + {"action": "launch", "target": "x"}, session_id="cancel", turn_id="t" + ) + assert refused["error"] == "auip_interaction_disabled" + _on(monkeypatch) + runtime.disconnect(registered["app_session_id"]) + # Shutdown is no longer pending: the last session ending leaves it on. + assert runtime.ai_interaction_in_effect() is True + routed = await coordinator.route_control( + {"action": "launch", "target": "x"}, session_id="cancel", turn_id="t" + ) + assert routed == {"ok": False, "error": "no_launchable_auip_app"} + + asyncio.run(scenario()) + + +def test_after_the_last_session_ends_participation_is_refused_and_on_restores( + monkeypatch, +) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + registered = _registered(runtime, _manifest(), "gated-turns") + sid = registered["app_session_id"] + calls: list[dict] = [] + + async def controller(context: dict) -> dict: + calls.append(context) + return {"action": "wait", "reason": "observed"} + + engagement = AuipEngagementCoordinator( + app_runtime=runtime, + controller=controller, + role_authorizer=_approve, + ) + runtime.set_engagement_mode(app_session_id=sid, mode="collaborate") + + _off(monkeypatch) + # The session was active when the switch went off, so it still gets turns. + await engagement.on_update( + Method.AUIP_UPDATED, _turn_ready(runtime, registered, "turn-pending") + ) + await engagement.wait_for_idle(sid) + assert len(calls) == 1 + + stale = _turn_ready(runtime, registered, "turn-late") + runtime.disconnect(sid) + await engagement.on_update(Method.AUIP_UPDATED, stale) + for request in ( + lambda: engagement.request_step(app_session_id=sid, instruction="Move."), + lambda: engagement.set_mode(app_session_id=sid, mode="collaborate"), + lambda: engagement.set_mode(app_session_id=sid, mode="delegate"), + ): + with pytest.raises(AuipProtocolError) as refused: + result = request() + if asyncio.iscoroutine(result): + await result + assert refused.value.code == "auip_interaction_disabled" + await asyncio.sleep(0) + assert len(calls) == 1 + + _on(monkeypatch) + assert runtime.ai_interaction_in_effect() is True + await engagement.close() + + asyncio.run(scenario()) + + +def _issue(runtime: AuipRuntime, mode: str = "collaborate") -> str: + return runtime.issue_attach_ticket( + conversation_id="admission", + artifact_ref="artifact:game@digest", + engagement_mode=mode, + )["attach_ticket"] + + +def test_attach_ticket_is_refused_while_the_switch_is_off(monkeypatch) -> None: + runtime = AuipRuntime() + ticket = _issue(runtime) + _off(monkeypatch) + with pytest.raises(AuipProtocolError) as refused: + runtime.register_attached(manifest=_manifest(), attach_ticket=ticket) + assert refused.value.code == "auip_interaction_disabled" + assert runtime.has_active_session() is False + assert runtime.ai_interaction_in_effect() is False + + # A participant-only app is refused too, not downgraded to a mode it lacks. + participant_only = _issue(runtime, "delegate") + with pytest.raises(AuipProtocolError) as refused: + runtime.register_attached( + manifest=_manifest(stances=("participant",)), + attach_ticket=participant_only, + ) + assert refused.value.code == "auip_interaction_disabled" + assert runtime.has_active_session() is False + assert runtime.ai_interaction_in_effect() is False + + _on(monkeypatch) + assert runtime.register_attached( + manifest=_manifest(), attach_ticket=_issue(runtime) + )["engagement_mode"] == "collaborate" + + +def test_attach_is_refused_during_pending_off_and_pending_off_still_ends( + monkeypatch, +) -> None: + runtime = AuipRuntime() + first = _registered(runtime, _manifest(), "admission") + second = _registered(runtime, _manifest(), "admission") + ticket = _issue(runtime) + _off(monkeypatch) + assert runtime.ai_interaction_in_effect() is True + + with pytest.raises(AuipProtocolError) as refused: + runtime.register_attached(manifest=_manifest(), attach_ticket=ticket) + assert refused.value.code == "auip_interaction_disabled" + + runtime.disconnect(first["app_session_id"]) + assert runtime.ai_interaction_in_effect() is True + runtime.disconnect(second["app_session_id"]) + # No refused app joined, so the pending shutdown completes. + assert runtime.has_active_session() is False + assert runtime.ai_interaction_in_effect() is False + + +@pytest.mark.parametrize("active", [False, True], ids=["off", "pending-off"]) +def test_self_attach_request_is_refused_while_the_switch_is_off( + monkeypatch, active +) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + if active: + _registered(runtime, _manifest(), "admission") + attention = MagicMock() + attention.create_selection = AsyncMock() + artifacts = MagicMock() + coordinator = AuipSelfAttachCoordinator( + runtime=runtime, + artifacts=artifacts, + attention=attention, + current_session_id=lambda: "admission", + ) + _off(monkeypatch) + with pytest.raises(AuipProtocolError) as refused: + await coordinator.request( + manifest=_manifest(), + instance_id="instance-0001", + entry_url="file:///tmp/game.html", + ) + assert refused.value.code == "auip_interaction_disabled" + # No card offers play options, and no ticket is minted. + attention.create_selection.assert_not_awaited() + assert runtime._attach_tickets == {} + + asyncio.run(scenario()) + + +def test_control_decided_after_the_last_session_ended_is_refused(monkeypatch) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + registered = _registered(runtime, _manifest(), "late-control") + sid = registered["app_session_id"] + runtime.focus(conversation_id="late-control", app_session_id=sid) + launch = AsyncMock() + host = AuipHandler( + runtime, + current_session_id=lambda: "late-control", + engagement=AuipEngagementCoordinator( + app_runtime=runtime, + controller=lambda _context: {"action": "wait"}, + role_authorizer=_approve, + ), + launch=launch, + ) + + _off(monkeypatch) + runtime.disconnect(sid) + for attrs in ( + {"action": "collaborate", "_host_app_session_id": sid}, + {"action": "step", "_host_app_session_id": sid}, + {"action": "launch", "target": "2048", "mode": "collaborate"}, + ): + routed = await host.route_control( + attrs, session_id="late-control", user_text="一緒に遊ぼう", turn_id="late" + ) + assert routed == {"ok": False, "error": "auip_interaction_disabled"} + assert launch.route_control.await_count == 0 + assert runtime.get(sid)["operator_status"] == "idle" + await host.engagement.close() + + asyncio.run(scenario()) + + +def test_narration_continues_while_pending_off_and_stops_after_the_last_session( + monkeypatch, +) -> None: + async def scenario() -> None: + runtime = AuipRuntime() + manifest = _manifest(stances=("spectator",)) + del manifest["events"]["game.turn_ready"] + registered = runtime.register(manifest=manifest, conversation_id="narration") + sid, token = registered["app_session_id"], registered["bridge_token"] + observed: list[str] = [] + + async def observer(payload: dict) -> dict: + observed.append(str(payload["event"]["event_id"])) + return {"action": "silent", "fact_brief": "move"} + + adapter = AuipNarrationAdapter( + runtime=runtime, + observer=observer, + narrator=lambda _payload: {}, + sink=lambda _payload: {"status": "queued"}, + profile=AuipNarrationProfile(normal_beat_stride=1), + ) + + def move(revision: int) -> dict: + runtime.publish_state( + app_session_id=sid, + bridge_token=token, + revision=revision, + state={"moves": revision}, + ) + return runtime.publish_event( + app_session_id=sid, + bridge_token=token, + event_id=f"move-{revision}", + type="game.move_committed", + actor="user", + revision=revision, + payload={"move": revision}, + ) + + _off(monkeypatch) + await adapter.enqueue_update(Method.AUIP_UPDATED, move(1)) + await adapter.wait_for_idle() + assert observed == ["move-1"] + + second = move(2) + runtime.disconnect(sid) + await adapter.enqueue_update(Method.AUIP_UPDATED, second) + await adapter.wait_for_idle() + assert observed == ["move-1"] + await adapter.close() + + asyncio.run(scenario()) + + +def test_live_setting_is_strict(monkeypatch) -> None: + async def scenario() -> None: + handler = SystemHandler() + _on(monkeypatch) + monkeypatch.setattr(handler, "_get_config", AsyncMock(return_value={})) + monkeypatch.setattr("server.handlers.system_handler.bus.emit", AsyncMock()) + + with pytest.raises(ValueError, match="boolean"): + await handler._set_config({"values": {"auip_interaction_enabled": "false"}}) + assert settings.AUIP_INTERACTION_ENABLED is True + + result = await handler._set_config({"values": {"auip_interaction_enabled": False}}) + assert settings.AUIP_INTERACTION_ENABLED is False + assert "auip_interaction_enabled" in result["updated"] + + await handler._set_config({"values": {"auip_interaction_enabled": True}}) + assert settings.AUIP_INTERACTION_ENABLED is True + + asyncio.run(scenario()) + + +def test_existing_installations_keep_interaction_on_by_default() -> None: + from config.catalog import application_policy, configuration_field + + field = configuration_field("AUIP_INTERACTION_ENABLED") + assert field["default"] is True + assert field["runtime_key"] == "auip_interaction_enabled" + assert application_policy("AUIP_INTERACTION_ENABLED") == "host" diff --git a/tests/test_cooperative_auip_entry.py b/tests/test_cooperative_auip_entry.py index 0026338a..7dfde494 100644 --- a/tests/test_cooperative_auip_entry.py +++ b/tests/test_cooperative_auip_entry.py @@ -151,6 +151,50 @@ async def test_role_entry_proposal_does_not_authorize_launch(entry_host, failure assert context.host.adapter.calls == 0 +async def test_interaction_off_skips_entry_query_and_prompt_until_turned_back_on( + entry_host, monkeypatch): + from config import settings + + context, state, _launch, _item, _attempt, artifact = entry_host + original_query = context.manager.query + prompts = [] + + async def query(messages, *, on_text=None): + frame = json.loads(messages[-1]["content"]) + if frame["source_kind"] == "user": + prompts.append(messages[0]["content"]) + if settings.AUIP_INTERACTION_ENABLED: + return await original_query(messages, on_text=on_text) + if frame["source_kind"] != "user": + return "わかったわ。" + # The role contract offers op=auip only beside Host launch candidates. + raw = json.dumps({"action":None, "say":"いいわ。"}, ensure_ascii=False) + if on_text is not None: + await on_text(raw) + return raw + + context.manager.query = query + text = "刚才那个 2048 再打开吧,咱们接着玩。" + monkeypatch.setattr(settings, "AUIP_INTERACTION_ENABLED", False) + assert context.manager.prefetch_auip_entry_context(context.session_id) is None + await context.handler.send_text(text, session_id=context.session_id, turn_id="off") + await context.finish() + ingress = context.manager.ingresses[context.session_id] + assert ingress.receipts["off"]["state"] != "auip_entry_pending" + assert state.captures == [] + assert len(prompts) == 1 and "[AUIP launchable applications]" not in prompts[0] + assert not [p for m, p in state.events if m == Method.AUIP_LAUNCH_REQUESTED] + + monkeypatch.setattr(settings, "AUIP_INTERACTION_ENABLED", True) + await context.handler.send_text(text, session_id=context.session_id, turn_id="on") + await context.finish() + assert ingress.receipts["on"]["state"] == "auip_entry_pending" + assert len(state.captures) == 1 + assert "[AUIP launchable applications]" in prompts[-1] + event, = [p for m, p in state.events if m == Method.AUIP_LAUNCH_REQUESTED] + assert event["artifact_id"] == artifact.artifact_id + + async def test_independent_inactive_launch_and_work_settle_through_existing_owners( entry_host): context, state, _launch, item, _attempt, artifact = entry_host