Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/wonky_app/lib/src/assistant/shell_assistant.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion packages/wonky_app/lib/src/shell/shell_services.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/widgets.dart';
import 'dart:async';

Expand Down Expand Up @@ -336,7 +337,25 @@ class ShellServices implements ActiveDocumentHost {
final List<McpDescribableDialog> 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<bool> get assistantOffered => _assistantOffered;
final ValueNotifier<bool> _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<ProtocolInfo?> serverInfo = ValueNotifier(null);
Expand Down
13 changes: 12 additions & 1 deletion specs/10-ai-assistant.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---------|-------|--------|
Expand Down Expand Up @@ -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
Expand Down
127 changes: 126 additions & 1 deletion wonky_server/test/integration/platform/ai/ai_org_key_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,32 @@ 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() =>
'acme${clock.now().microsecondsSinceEpoch}k${_counter++}.dev';

/// 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();
});
Expand Down Expand Up @@ -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<List<InlineAiEvent>> 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<WonkyException>().having(
(e) => e.code,
'code',
WonkyErrorCode.unavailable,
),
),
);
expect(fake.requests, isEmpty);
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,14 @@ class _SheetEditorScreenState extends State<SheetEditorScreen> {
}

@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => ValueListenableBuilder<bool>(
// 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<String>('sheets.screen.${widget.itemUuid}'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,14 @@ class _DeckEditorScreenState extends State<DeckEditorScreen> {
}

@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => ValueListenableBuilder<bool>(
// 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<String>('slides.screen.${widget.itemUuid}'),
Expand Down
6 changes: 4 additions & 2 deletions wonky_write/lib/features/screen/write_document_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,9 @@ class _WriteDocumentScreenState extends State<WriteDocumentScreen> {
@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),
);
}
Expand Down Expand Up @@ -200,7 +202,7 @@ class _WriteDocumentScreenState extends State<WriteDocumentScreen> {
],
// 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,
Expand Down
30 changes: 30 additions & 0 deletions wonky_write/test/features/screen/write_document_screen_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading