From 4dc0e8f1f2a2a04b5e9c12b3daa48f7bf29c0347 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Mon, 9 Nov 2026 17:54:56 +0100 Subject: [PATCH] fix(ai): show the assistant panel after signing in from a shared link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A colleague who opened a shared document through the sign-in screen got no Assistant in the rail. The router opens the document as soon as the auth status flips to signed in, but the assistant is installed only when the sign-in setup finishes (profile, preferences), and the editor screens built their panel list once from `services.assistant` without listening to it. The server was not at fault: keys resolve per requesting user, so an organization member gets the organization's key on any document. - ShellServices.assistantOffered (installed and not switched off) is updated when the assistant is installed, removed or its status changes. - Write, Sheets and Slides rebuild their panels from it. - Server tests pin whose key pays on a shared document; spec 10 §1/§3 document it. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/assistant/shell_assistant.dart | 10 +- .../lib/src/shell/shell_services.dart | 21 ++- specs/10-ai-assistant.md | 13 +- .../platform/ai/ai_org_key_test.dart | 127 +++++++++++++++++- .../sheet_editor/sheet_editor_screen.dart | 9 +- .../editor_screen/deck_editor_screen.dart | 9 +- .../screen/write_document_screen.dart | 6 +- .../screen/write_document_screen_test.dart | 30 +++++ 8 files changed, 217 insertions(+), 8 deletions(-) diff --git a/packages/wonky_app/lib/src/assistant/shell_assistant.dart b/packages/wonky_app/lib/src/assistant/shell_assistant.dart index 6fc5bd4f..f00efd3a 100644 --- a/packages/wonky_app/lib/src/assistant/shell_assistant.dart +++ b/packages/wonky_app/lib/src/assistant/shell_assistant.dart @@ -57,7 +57,9 @@ void openAiProviderSettings(ShellServices services, BuildContext context) => /// `shell.ai.*` commands and the ✨ buttons use. Apps create one /// [AssistantController] per open file with [controllerFor]. class ShellAssistant extends AssistantHook { - ShellAssistant(this.services, this.api); + ShellAssistant(this.services, this.api) { + status.addListener(_onStatus); + } final ShellServices services; final AssistantApi api; @@ -103,9 +105,15 @@ class ShellAssistant extends AssistantHook { c.dispose(); } a._controllers.clear(); + a.status.removeListener(a._onStatus); services.assistant = null; } + /// Keeps [ShellServices.assistantOffered] in step with [available]. + void _onStatus() { + if (identical(services.assistant, this)) services.assistantChanged(); + } + /// The panel is offered unless AI is switched off on the server; when /// the key is missing it explains that AI isn't configured. @override diff --git a/packages/wonky_app/lib/src/shell/shell_services.dart b/packages/wonky_app/lib/src/shell/shell_services.dart index 4ad384ae..67482682 100644 --- a/packages/wonky_app/lib/src/shell/shell_services.dart +++ b/packages/wonky_app/lib/src/shell/shell_services.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart' show ValueListenable; import 'package:flutter/widgets.dart'; import 'dart:async'; @@ -336,7 +337,25 @@ class ShellServices implements ActiveDocumentHost { final List openDialogs = []; /// The AI assistant (suite 10), contributed by the assistant workstream. - AssistantHook? assistant; + AssistantHook? get assistant => _assistant; + AssistantHook? _assistant; + set assistant(AssistantHook? a) { + _assistant = a; + assistantChanged(); + } + + /// Whether the assistant panel is offered: [assistant] is installed and + /// [AssistantHook.available]. Editor screens rebuild their side panels + /// from it: the assistant is installed once sign-in completes, which can + /// be after a document opened (a shared link followed through the sign-in + /// screen), and its availability follows its status. + ValueListenable get assistantOffered => _assistantOffered; + final ValueNotifier _assistantOffered = ValueNotifier(false); + + /// Re-reads [AssistantHook.available] into [assistantOffered] (the + /// installed hook calls it when its status changes). + void assistantChanged() => + _assistantOffered.value = _assistant?.available ?? false; /// Server protocol info (version check, feature flags). final ValueNotifier serverInfo = ValueNotifier(null); diff --git a/specs/10-ai-assistant.md b/specs/10-ai-assistant.md index 8e306264..7e524348 100644 --- a/specs/10-ai-assistant.md +++ b/specs/10-ai-assistant.md @@ -50,6 +50,14 @@ never reach clients). The assistant acts on documents through the **same tool la four). Usage still counts against each user's own daily budget. Endpoints: `assistant.setOrganizationProviderKey(provider, apiKey)`, `assistant.removeOrganizationProviderKey()`. +- **Keys follow the requesting user, not the file.** Every request (assistant, inline AI, + proofreading) and the status resolve the key of the signed-in user who makes it, whatever + file it is about. On a shared file, a colleague in the owner's organization therefore uses + that organization's shared key (it is their organization too), a collaborator from another + organization uses their own resolution (their key, their organization's), and one without + any key sees "AI isn't configured", even though the owner has a key: an owner's or an + organization's key never pays for people outside the organization. Server tests: + `ai_org_key_test.dart` (*a document shared by a member of an organization*). - **Models.** "AI quality" maps to a model size and effort: | Setting | Model | Effort | |---------|-------|--------| @@ -182,7 +190,10 @@ fields: *Tools › Assistant*, *View › Panels › Assistant*, `Mod+J` (contextual binding: in Write, inside an empty paragraph `Mod+J` opens the inline AI prompt instead — see suite 08 §1.2). Right side panel in the shared panel host (suite 02 §4.5: shared width 300–640 px, collapses to the icon - rail); the rail shows it only when the assistant is available. + rail); the rail shows it only when the assistant is available. Editor screens rebuild their + panels from `ShellServices.assistantOffered` (the assistant is installed and not switched off + on the server): the assistant is installed when sign-in completes, which can be after the + file already opened, as when a shared link is followed through the sign-in screen. - Header: thread picker (dropdown of threads for this file + "New chat"), ⋮ (Clear, Delete thread, Settings). - Message list: user bubbles, assistant Markdown rendering (code blocks with copy), **tool diff --git a/wonky_server/test/integration/platform/ai/ai_org_key_test.dart b/wonky_server/test/integration/platform/ai/ai_org_key_test.dart index 883c24fe..1662a6eb 100644 --- a/wonky_server/test/integration/platform/ai/ai_org_key_test.dart +++ b/wonky_server/test/integration/platform/ai/ai_org_key_test.dart @@ -7,16 +7,19 @@ import 'package:clock/clock.dart'; import 'package:test/test.dart'; import 'package:wonky_server/src/platform/ai/ai_config.dart'; import 'package:wonky_server/src/platform/ai/ai_keys.dart'; +import 'package:wonky_server/src/platform/ai/ai_models.dart'; import 'package:wonky_server/src/platform/ai/llm/fake_ai_client.dart'; import 'package:wonky_server/src/platform/common/models.dart'; import 'package:wonky_server/src/platform/organizations/organization_config.dart'; import 'package:wonky_server/src/platform/organizations/organization_service.dart'; +import '../../../support/test_drive.dart'; import '../../../support/test_users.dart'; import '../../../support/wonky_serverpod.dart'; const _shared = 'sk-test-0123456789-shared-ORGK'; const _own = 'sk-test-0123456789-personal-wxyz'; +const _other = 'AIza-test-0123456789-other-OTHK'; var _counter = 0; String _freshDomain() => @@ -24,9 +27,12 @@ String _freshDomain() => /// The organization's shared AI key (suite 10 §1 "Keys"). void main() { + late FakeAiModelClient fake; + setUp(() { AiConfig.current = AiConfig(); - AiConfig.clientOverride = FakeAiModelClient(provider: AiProvider.openai); + fake = FakeAiModelClient(provider: AiProvider.openai); + AiConfig.clientOverride = fake; OrganizationConfig.reset(); OrganizationService.forget(); }); @@ -199,4 +205,123 @@ void main() { expect(s.organization, isNull); }); }); + + withWonkyServerpod('Given a document shared by a member of an organization ' + 'with a shared key', (sessionBuilder, endpoints) { + late TestUser anna; + late TestUser bo; + late TestUser outsider; + late TestUser gmail; + late DriveItemView doc; + + /// The provider whose model served the last request. + AiProvider lastProvider() { + final model = fake.requests.last.model; + return AiProvider.values.firstWhere((p) { + final (large, small) = AiModels.defaults(p); + return model == large || model == small; + }); + } + + Future> improve(TestUser u) => endpoints.assistant + .inline( + u.endpointSession, + InlineAiRequest( + itemUuid: doc.uuid, + action: 'improve', + selectedMarkdown: 'We should ship it.', + ), + ) + .toList(); + + setUp(() async { + final domain = _freshDomain(); + anna = await TestUsers.create( + sessionBuilder, + name: 'Anna Berg', + email: 'anna@$domain', + ); + bo = await TestUsers.create( + sessionBuilder, + name: 'Bo Chen', + email: 'bo@$domain', + ); + outsider = await TestUsers.create( + sessionBuilder, + name: 'Olle Out', + email: 'olle@${_freshDomain()}', + ); + gmail = await TestUsers.create( + sessionBuilder, + name: 'Gus Mail', + email: 'gus.${clock.now().microsecondsSinceEpoch}@gmail.com', + ); + await endpoints.assistant.setOrganizationProviderKey( + anna.endpointSession, + AiProvider.anthropic, + _shared, + ); + doc = await TestDrive.document( + endpoints, + anna, + markdown: '# Plan\n\nWe should ship it.\n', + ); + for (final u in [bo, outsider, gmail]) { + await TestDrive.share(endpoints, doc, anna, u, AccessRole.editor); + } + }); + + test('when a colleague who can edit uses AI on it then the assistant is ' + "available to them and their organization's key serves it", () async { + final status = await endpoints.assistant.getStatus(bo.endpointSession); + expect(status.available, isTrue); + expect(status.keySource, 'organization'); + + fake.enqueue((AiScript()..text('Let us ship it.')).response); + final events = await improve(bo); + + expect(events.last.type, InlineAiEventType.done); + expect(lastProvider(), AiProvider.anthropic); + final c = await AiKeys.forUser(sessionBuilder.build(), bo.id); + expect(c?.apiKey, _shared); + expect(c?.source, AiKeySource.organization); + }); + + test('when an editor from another organization uses AI on it then their ' + "own organization's key serves it, not the owner's", () async { + await endpoints.assistant.setOrganizationProviderKey( + outsider.endpointSession, + AiProvider.gemini, + _other, + ); + + fake.enqueue((AiScript()..text('Let us ship it.')).response); + final events = await improve(outsider); + + expect(events.last.type, InlineAiEventType.done); + expect(lastProvider(), AiProvider.gemini); + final c = await AiKeys.forUser(sessionBuilder.build(), outsider.id); + expect(c?.apiKey, _other); + }); + + test('when an editor without an organization or key uses AI on it then ' + "it is unavailable to them: the owner's key does not pay", () async { + final status = await endpoints.assistant.getStatus( + gmail.endpointSession, + ); + expect(status.available, isFalse); + + await expectLater( + improve(gmail), + throwsA( + isA().having( + (e) => e.code, + 'code', + WonkyErrorCode.unavailable, + ), + ), + ); + expect(fake.requests, isEmpty); + }); + }); } diff --git a/wonky_sheets/lib/features/sheet_editor/sheet_editor_screen.dart b/wonky_sheets/lib/features/sheet_editor/sheet_editor_screen.dart index 9a333fee..021686cc 100644 --- a/wonky_sheets/lib/features/sheet_editor/sheet_editor_screen.dart +++ b/wonky_sheets/lib/features/sheet_editor/sheet_editor_screen.dart @@ -255,7 +255,14 @@ class _SheetEditorScreenState extends State { } @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => ValueListenableBuilder( + // The assistant can be installed after the spreadsheet opened (sign-in + // from a shared link): its panel joins the rail then. + valueListenable: s.assistantOffered, + builder: (context, _, _) => _scaffold(context), + ); + + Widget _scaffold(BuildContext context) { final editor = _editor; return EditorScaffold( key: ValueKey('sheets.screen.${widget.itemUuid}'), diff --git a/wonky_slides/lib/features/editor_screen/deck_editor_screen.dart b/wonky_slides/lib/features/editor_screen/deck_editor_screen.dart index 28b7ba11..1d26c6e4 100644 --- a/wonky_slides/lib/features/editor_screen/deck_editor_screen.dart +++ b/wonky_slides/lib/features/editor_screen/deck_editor_screen.dart @@ -300,7 +300,14 @@ class _DeckEditorScreenState extends State { } @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => ValueListenableBuilder( + // The assistant can be installed after the deck opened (sign-in from a + // shared link): its panel joins the rail then. + valueListenable: s.assistantOffered, + builder: (context, _, _) => _scaffold(context), + ); + + Widget _scaffold(BuildContext context) { final editor = _editor; return EditorScaffold( key: ValueKey('slides.screen.${widget.itemUuid}'), diff --git a/wonky_write/lib/features/screen/write_document_screen.dart b/wonky_write/lib/features/screen/write_document_screen.dart index aeb912c1..b246d48d 100644 --- a/wonky_write/lib/features/screen/write_document_screen.dart +++ b/wonky_write/lib/features/screen/write_document_screen.dart @@ -172,7 +172,9 @@ class _WriteDocumentScreenState extends State { @override Widget build(BuildContext context) { return ListenableBuilder( - listenable: doc.viewPrefs, + // The assistant can be installed after the document opened (sign-in + // from a shared link): its panel joins the rail then. + listenable: Listenable.merge([doc.viewPrefs, s.assistantOffered]), builder: (context, _) => _scaffold(context), ); } @@ -200,7 +202,7 @@ class _WriteDocumentScreenState extends State { ], // Rail order: Assistant, Outline, Find (then the shell's History). panels: [ - if (s.assistant?.available ?? false) writeAssistantPanelSpec(ai), + if (s.assistantOffered.value) writeAssistantPanelSpec(ai), SidePanelSpec( id: WritePanels.outline, title: writeL10n(context).screenPanelOutline, diff --git a/wonky_write/test/features/screen/write_document_screen_test.dart b/wonky_write/test/features/screen/write_document_screen_test.dart index d7f56bdd..0f9cad38 100644 --- a/wonky_write/test/features/screen/write_document_screen_test.dart +++ b/wonky_write/test/features/screen/write_document_screen_test.dart @@ -413,6 +413,36 @@ void main() { await tester.pump(const Duration(seconds: 2)); }); + testWidgets('Given a document that opened before sign-in finished (a ' + 'shared link) when the assistant is installed then its panel joins the ' + 'rail, and leaves it when AI is switched off on the server', ( + tester, + ) async { + await pumpScreen(tester); + const rail = ValueKey('panel.rail.assistant'); + expect(find.byKey(rail), findsNothing); + + final api = FakeAssistantApi(); + final assistant = ShellAssistant.install(h.services, api: api); + addTearDown(() => ShellAssistant.uninstall(h.services)); + await tester.runAsync(pumpEventQueue); + await tester.pump(); + expect(find.byKey(rail), findsOneWidget); + + api.status = AssistantStatus( + available: false, + reason: 'disabled', + quality: AiQuality.best, + tokensUsedToday: 0, + dailyTokenBudget: 1000000, + ); + await tester.runAsync(assistant.refreshStatus); + await tester.pump(); + expect(find.byKey(rail), findsNothing); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(seconds: 2)); + }); + testWidgets('Given a caret in the editor when the focus moves to the ' 'toolbar then the caret hides, and choosing a heading in the style ' 'picker returns the focus and the caret (Write 05 §4.1)', (tester) async {