@kubohiroya/turbowarp-plus-editor-workbench 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,20 @@
1
- import type { DrawerViews } from './drawer-views.ts';
1
+ import type { DrawerView, DrawerViews } from './drawer-views.ts';
2
2
  import type { StageDrawerLayout } from './workspace-layout.ts';
3
3
  export type { DrawerMenu, DrawerMenuRenderProps, DrawerRenderProps, DrawerView, DrawerViewId, DrawerViews, HostDrawerViewId } from './drawer-views.ts';
4
- export declare function createStandardLayout(React: any, { styles, targetStyles, context, LayoutMenu }: {
4
+ type DrawerPanel = (props: {
5
+ id: DrawerView['id'];
6
+ title: string;
7
+ locale: string;
8
+ dockRequest: number;
9
+ renderHeading(undock: import('react').ReactNode): import('react').ReactNode;
10
+ renderContent(detached: boolean): import('react').ReactNode;
11
+ }) => import('react').ReactNode;
12
+ export declare function createStandardLayout(React: any, { styles, targetStyles, context, LayoutMenu, DrawerPanel }: {
5
13
  styles: any;
6
14
  targetStyles: any;
7
15
  context: any;
8
16
  LayoutMenu: any;
17
+ DrawerPanel?: DrawerPanel;
9
18
  }): {
10
19
  StandardLayout: ({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer, onPaletteModeChange, windowTools, Container, render, drawerViews, stageDrawerLayout, updateStageDrawer, ...props }: {
11
20
  [x: string]: any;
@@ -1,6 +1,6 @@
1
1
  import { createLayout, createSplitter, splitAxis } from "./index.js";
2
2
  import { createTargetList } from "./targets.js";
3
- import { availableDrawerViews, createDrawerViewBar, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
3
+ import { availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
4
4
  import { attachStageDrawerDrag } from "./stage-drawer-drag.js";
5
5
  const isJapanese = locale => /^ja(?:-|$)/i.test(locale);
6
6
  const singleColumnTargetWidth = 108;
@@ -8,7 +8,7 @@ const singleColumnTargetWidth = 108;
8
8
  const drawerViewWidth = 300;
9
9
  const minimumDrawerViewWidth = 160;
10
10
  const minimumStandardEditor = 380;
11
- export function createStandardLayout(React, { styles, targetStyles, context, LayoutMenu }) {
11
+ export function createStandardLayout(React, { styles, targetStyles, context, LayoutMenu, DrawerPanel = undefined }) {
12
12
  const { createElement: element, useContext, useLayoutEffect, useRef, useState } = React;
13
13
  const SplitLayout = createLayout(React);
14
14
  const Splitter = createSplitter(React);
@@ -31,12 +31,17 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
31
31
  const hostDrawerViews = availableDrawerViews(drawerViews);
32
32
  // A view saved earlier comes back once the host supplies it again.
33
33
  const drawerView = hostDrawerViews.some(view => view.id === preferredDrawerView) ? preferredDrawerView : 'sprites';
34
- const selectDrawerView = view => {
34
+ const selectDrawerView = React.useCallback(view => {
35
35
  setPreferredDrawerView(view);
36
36
  writeDrawerView(props.storage, props.storageKey, view);
37
- };
37
+ }, [props.storage, props.storageKey]);
38
38
  const body = useRef(null);
39
39
  const plusLayout = enabled && !props.fullscreen;
40
+ const reportDrawerSelection = drawerViews?.onSelectionChange;
41
+ useLayoutEffect(() => {
42
+ reportDrawerSelection?.(plusLayout ? drawerView : 'sprites');
43
+ return () => reportDrawerSelection?.('sprites');
44
+ }, [reportDrawerSelection, plusLayout, drawerView]);
40
45
  const stageHidden = plusLayout && !showStage;
41
46
  const stageDrawerPinned = updateStageDrawer ? stageDrawerLayout?.pinned !== false : localStageDrawerPinned;
42
47
  const setStageDrawerPinned = (pinned) => {
@@ -385,12 +390,23 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
385
390
  function TargetLayout({ compact, render }) {
386
391
  const { plusLayout, targetsPinned, locale, drawerViews, drawerView = 'sprites', selectDrawerView } = useContext(context);
387
392
  const tools = useState(null);
393
+ const focusDrawer = useRef(null);
394
+ const [reveal, setReveal] = useState(null);
395
+ useLayoutEffect(() => {
396
+ if (!plusLayout)
397
+ return;
398
+ return drawerViews?.registerReveal?.(id => {
399
+ selectDrawerView(id);
400
+ setReveal(previous => ({ id, request: (previous?.request ?? 0) + 1 }));
401
+ focusDrawer.current?.();
402
+ });
403
+ }, [plusLayout, drawerViews, selectDrawerView]);
388
404
  const panel = render(plusLayout || compact);
389
405
  if (!plusLayout)
390
406
  return panel;
391
407
  const content = element(targetTools.Provider, { value: tools }, panel);
392
408
  const drawer = children => element(EdgeDrawer, {
393
- edge: 'left', pinned: targetsPinned,
409
+ edge: 'left', pinned: targetsPinned, focusPanelRef: focusDrawer,
394
410
  label: isJapanese(locale) ? 'スプライト一覧を展開' : 'Reveal sprite list'
395
411
  }, children);
396
412
  // Without host views the drawer keeps the sprite list as its only, unwrapped content.
@@ -400,10 +416,9 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
400
416
  const active = views.find(view => view.id === drawerView);
401
417
  return drawer(element(React.Fragment, null, element(DrawerViewBar, { locale, views, agents: drawerViews.agents, selected: active ? active.id : 'sprites',
402
418
  onSelect: selectDrawerView }),
403
- // Pinning belongs to the drawer, so every view keeps the pin button the sprite list shows.
404
- active && element('div', { className: styles.drawerViewTools }, active.tools?.({ locale }), element(DrawerPinButton, { label: isJapanese(locale) ? 'このパネルを固定表示' : 'Pin this panel' })),
405
419
  // The GUI's target pane stays mounted, so its file inputs and library keep working while hidden.
406
- element('div', { className: styles.drawerSprites, hidden: Boolean(active) }, content), active && element('div', { className: styles.drawerViewContent, 'data-drawer-content': active.id }, active.render({ locale }))));
420
+ element('div', { className: styles.drawerSprites, hidden: Boolean(active) }, content), views.map(view => element(HostDrawerView, { key: view.id, view, locale, active: view === active,
421
+ dockRequest: reveal?.id === view.id ? reveal.request : 0 }))));
407
422
  }
408
423
  function SpriteGrid(props) {
409
424
  const { plusLayout } = useContext(context);
@@ -443,16 +458,11 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
443
458
  return element('button', { type: 'button', className: styles.drawerPin, 'aria-label': label, 'aria-pressed': targetsPinned,
444
459
  title: label, onClick: () => setTargetsPinned(value => !value) }, drawerPinIcon(element, targetsPinned));
445
460
  }
446
- function useSpriteListTools() {
447
- const { locale } = useContext(context);
448
- const [mount] = useContext(targetTools) ?? [];
461
+ function useDrawerTools(searchLabel) {
449
462
  const [searching, setSearching] = useState(false);
450
463
  const [query, setQuery] = useState('');
451
464
  const searchButton = useRef(null);
452
465
  const searchInput = useRef(null);
453
- const japanese = isJapanese(locale);
454
- const pinLabel = japanese ? 'スプライト一覧を固定表示' : 'Pin sprite list';
455
- const searchLabel = japanese ? 'スプライトを検索' : 'Search sprites';
456
466
  useLayoutEffect(() => {
457
467
  if (searching)
458
468
  searchInput.current?.focus({ preventScroll: true });
@@ -462,11 +472,10 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
462
472
  setQuery('');
463
473
  searchButton.current?.focus();
464
474
  };
465
- const renderTools = openAction => element(React.Fragment, null, element('div', { className: styles.targetListTools, role: 'group',
466
- 'aria-label': japanese ? 'スプライト一覧の操作' : 'Sprite list tools' }, element('button', { type: 'button', ref: searchButton, 'aria-label': searchLabel, 'aria-expanded': searching,
467
- title: searchLabel, onClick: () => searching ? closeSearch() : setSearching(true) }, element('svg', { 'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
468
- fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' }, element('circle', { cx: 6.5, cy: 6.5, r: 4 }), element('path', { d: 'm9.5 9.5 4 4' }))), element(DrawerPinButton, { label: pinLabel }), openAction), searching && element('input', { type: 'search', className: styles.targetListSearch, 'aria-label': searchLabel,
469
- ref: searchInput, placeholder: japanese ? '名前' : 'Name', value: query,
475
+ const render = ({ label, pinLabel, openAction, tools }) => element(React.Fragment, null, element('div', { className: styles.targetListTools, role: 'group', 'aria-label': label }, tools, searchLabel && element('button', { type: 'button', ref: searchButton, 'aria-label': searchLabel,
476
+ 'aria-expanded': searching, title: searchLabel, onClick: () => searching ? closeSearch() : setSearching(true) }, element('svg', { 'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
477
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' }, element('circle', { cx: 6.5, cy: 6.5, r: 4 }), element('path', { d: 'm9.5 9.5 4 4' }))), pinLabel && element(DrawerPinButton, { label: pinLabel }), openAction), searching && element('input', { type: 'search', className: styles.targetListSearch,
478
+ 'aria-label': searchLabel, ref: searchInput, placeholder: searchLabel, value: query,
470
479
  onChange: event => setQuery(event.currentTarget.value),
471
480
  onKeyDown: event => {
472
481
  if (event.key === 'Escape') {
@@ -474,8 +483,40 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
474
483
  closeSearch();
475
484
  }
476
485
  } }));
486
+ return { query, render };
487
+ }
488
+ function HostDrawerView({ view, locale, active, dockRequest }) {
489
+ const title = view.label ?? drawerLabel(view.id, locale);
490
+ const japanese = isJapanese(locale);
491
+ const label = japanese ? `${title}の操作` : `${title} tools`;
492
+ const { query, render } = useDrawerTools(view.searchLabel?.(locale));
493
+ const renderHeading = openAction => render({
494
+ label,
495
+ pinLabel: japanese ? 'このパネルを固定表示' : 'Pin this panel',
496
+ openAction,
497
+ tools: view.tools?.({ locale, query })
498
+ });
499
+ const renderContent = detached => (active || detached) && element('div', {
500
+ className: styles.drawerViewContent, 'data-drawer-content': view.id
501
+ }, detached && view.searchLabel && render({ label }), view.render({ locale, query }));
502
+ if (!DrawerPanel && !active)
503
+ return null;
504
+ return element('div', { className: styles.drawerHostView, hidden: !active }, DrawerPanel ?
505
+ element(DrawerPanel, { id: view.id, title, locale, dockRequest, renderHeading, renderContent }) :
506
+ element(React.Fragment, null, renderHeading(null), renderContent(false)));
507
+ }
508
+ function useSpriteListTools() {
509
+ const { locale } = useContext(context);
510
+ const [mount] = useContext(targetTools) ?? [];
511
+ const japanese = isJapanese(locale);
512
+ const { query, render } = useDrawerTools(japanese ? 'スプライトを検索' : 'Search sprites');
477
513
  return {
478
- mount, query, renderTools,
514
+ mount, query,
515
+ renderTools: openAction => render({
516
+ label: japanese ? 'スプライト一覧の操作' : 'Sprite list tools',
517
+ pinLabel: japanese ? 'スプライト一覧を固定表示' : 'Pin sprite list',
518
+ openAction
519
+ }),
479
520
  title: japanese ? 'スプライト一覧' : 'Sprite list',
480
521
  openLabel: japanese ? 'アンドック' : 'Undock sprite list'
481
522
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -1,11 +1,11 @@
1
1
  import {isJapanese} from './drawer-views.ts';
2
+ import {desktopAgentSettings, type DesktopAiAgentsPort} from './desktop-ai-agents.ts';
2
3
 
3
4
  /** The services the Editor knows by name. Their name and icon are fixed; their address can be replaced. */
4
5
  export type AgentPresetId = 'chatgpt' | 'claude';
5
6
 
6
7
  /**
7
- * Where a service is opened. Only web pages for now; a desktop app launched with arguments is planned
8
- * as another `kind`, which this version ignores when it reads the settings.
8
+ * A web service. Desktop applications are stored separately by the Desktop host.
9
9
  */
10
10
  export interface AgentUrlTarget {
11
11
  kind: 'url';
@@ -26,6 +26,7 @@ export interface AgentSettings {
26
26
  version: 1;
27
27
  /** The presets in their fixed order, then the user's own services. */
28
28
  services: AgentService[];
29
+ unknownServices?: unknown[];
29
30
  }
30
31
 
31
32
  export type AgentStorage = Pick<Storage, 'getItem' | 'setItem'>;
@@ -65,7 +66,7 @@ const presetService = (preset: (typeof agentPresets)[number], saved?: {enabled?:
65
66
 
66
67
  export const defaultAgentSettings = (): AgentSettings => ({version: 1, services: agentPresets.map(preset => presetService(preset))});
67
68
 
68
- /** Settings read from saved JSON. Anything missing, unknown or invalid falls back to the defaults, entry by entry. */
69
+ /** Reads usable web services and preserves settings for target kinds this version cannot open. */
69
70
  export function parseAgentSettings(raw: string | null | undefined): AgentSettings {
70
71
  let saved: unknown;
71
72
  try {
@@ -77,9 +78,11 @@ export function parseAgentSettings(raw: string | null | undefined): AgentSetting
77
78
  !Array.isArray((saved as {services?: unknown}).services)) return defaultAgentSettings();
78
79
  const entries = (saved as {services: unknown[]}).services.filter(entry => entry && typeof entry === 'object') as
79
80
  {id?: unknown; preset?: unknown; name?: unknown; enabled?: unknown; target?: {kind?: unknown; url?: unknown}}[];
80
- const presets = agentPresets.map(preset => presetService(preset, entries.find(entry => entry.preset === preset.id)));
81
+ const presets = agentPresets.map(preset => presetService(preset, entries.find(entry => entry.preset === preset.id &&
82
+ (entry.target?.kind === 'url' || entry.target?.kind === undefined))));
81
83
  const ids = new Set<string>(presets.map(service => service.id));
82
84
  const custom: AgentService[] = [];
85
+ const unknownServices = entries.filter(entry => typeof entry.target?.kind === 'string' && entry.target.kind !== 'url');
83
86
  for (const entry of entries) {
84
87
  if (entry.preset !== undefined || entry.target?.kind !== 'url') continue;
85
88
  const name = typeof entry.name === 'string' ? entry.name.trim() : '';
@@ -90,7 +93,7 @@ export function parseAgentSettings(raw: string | null | undefined): AgentSetting
90
93
  ids.add(id);
91
94
  custom.push({id, name, enabled: entry.enabled !== false, target: {kind: 'url', url: checked.url}});
92
95
  }
93
- return {version: 1, services: [...presets, ...custom]};
96
+ return {version: 1, services: [...presets, ...custom], ...(unknownServices.length ? {unknownServices} : {})};
94
97
  }
95
98
 
96
99
  export const browserStorage = (): AgentStorage | null => {
@@ -114,9 +117,9 @@ export function writeAgentSettings(settings: AgentSettings, storage: AgentStorag
114
117
  key = agentSettingsKey): boolean {
115
118
  if (!storage) return false;
116
119
  try {
117
- storage.setItem(key, JSON.stringify({version: 1, services: settings.services.map(service => service.preset ?
120
+ storage.setItem(key, JSON.stringify({version: 1, services: [...settings.services.map(service => service.preset ?
118
121
  {preset: service.preset, enabled: service.enabled, target: service.target} :
119
- {id: service.id, name: service.name, enabled: service.enabled, target: service.target})}));
122
+ {id: service.id, name: service.name, enabled: service.enabled, target: service.target}), ...(settings.unknownServices ?? [])]}));
120
123
  return true;
121
124
  } catch {
122
125
  return false;
@@ -172,6 +175,8 @@ export interface AgentSettingsDialogOptions {
172
175
  /** Where focus goes when the dialog closes. Defaults to the element focused when it opened. */
173
176
  returnFocus?: HTMLElement | null;
174
177
  onSave?(settings: AgentSettings): void;
178
+ desktop?: DesktopAiAgentsPort | null;
179
+ onDesktopSave?(): void;
175
180
  }
176
181
 
177
182
  export interface AgentSettingsDialog {
@@ -189,7 +194,7 @@ interface Row {
189
194
 
190
195
  let openDialog: AgentSettingsDialog | null = null;
191
196
  let nextDialog = 0;
192
- const focusable = 'button:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
197
+ const focusable = 'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
193
198
  const urlProblems = {empty: 'urlEmpty', invalid: 'urlInvalid', 'not-https': 'urlNotHttps'} as const;
194
199
 
195
200
  /**
@@ -197,7 +202,7 @@ const urlProblems = {empty: 'urlEmpty', invalid: 'urlInvalid', 'not-https': 'url
197
202
  * user's own services. It is plain DOM so that any part of the Editor can open it, with or without React.
198
203
  */
199
204
  export function openAgentSettingsDialog({document: doc = globalThis.document, locale, styles = {}, storage = browserStorage(),
200
- storageKey = agentSettingsKey, returnFocus, onSave}: AgentSettingsDialogOptions): AgentSettingsDialog {
205
+ storageKey = agentSettingsKey, returnFocus, onSave, desktop, onDesktopSave}: AgentSettingsDialogOptions): AgentSettingsDialog {
201
206
  if (openDialog?.element.isConnected) {
202
207
  (openDialog.element.querySelector(focusable) as HTMLElement)?.focus();
203
208
  return openDialog;
@@ -301,7 +306,8 @@ export function openAgentSettingsDialog({document: doc = globalThis.document, lo
301
306
  const cancel = make('button', {type: 'button', class: styles.aiAgentDialogButton}, text('cancel'));
302
307
  const save = make('button', {type: 'submit', class: `${styles.aiAgentDialogButton ?? ''} ${styles.aiAgentDialogPrimary ?? ''}`.trim()},
303
308
  text('save'));
304
- const form = make('form', {novalidate: '', class: styles.aiAgentDialogForm}, presetGroup, customGroup, status,
309
+ const form = make('form', {novalidate: '', class: styles.aiAgentDialogForm}, presetGroup, customGroup,
310
+ desktop && desktopAgentSettings(doc, desktop, locale, styles, onDesktopSave), status,
305
311
  make('div', {class: styles.aiAgentDialogActions}, cancel, save));
306
312
  const element = make('div', {
307
313
  role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': `${prefix}-title`,
@@ -327,7 +333,7 @@ export function openAgentSettingsDialog({document: doc = globalThis.document, lo
327
333
  return;
328
334
  }
329
335
  if (event.key !== 'Tab') return;
330
- const items = [...element.querySelectorAll<HTMLElement>(focusable)];
336
+ const items = [...element.querySelectorAll<HTMLElement>(focusable)].filter(item => !item.matches(':disabled'));
331
337
  const first = items[0];
332
338
  const last = items[items.length - 1];
333
339
  if (event.shiftKey && doc.activeElement === first) {
@@ -363,7 +369,7 @@ export function openAgentSettingsDialog({document: doc = globalThis.document, lo
363
369
  }
364
370
  let count = 0;
365
371
  for (const service of services) if (!service.preset) service.id = `custom-${++count}`;
366
- const saved: AgentSettings = {version: 1, services};
372
+ const saved: AgentSettings = {...settings, services};
367
373
  if (!writeAgentSettings(saved, storage, storageKey)) {
368
374
  status.textContent = text('saveFailed');
369
375
  status.hidden = false;
package/src/ai-agents.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import type {DrawerMenu, DrawerMenuRenderProps} from './drawer-views.ts';
2
2
  import {agentsIconPath} from './drawer-views.ts';
3
3
  import {
4
- agentPresets, agentSettingsKey, agentText, browserStorage, enabledAgentServices, openAgentService,
4
+ agentPresets, agentSettingsKey, agentText, browserStorage, checkAgentUrl, enabledAgentServices, openAgentService,
5
5
  openAgentSettingsDialog, readAgentSettings, type AgentService, type AgentStorage, type Opener
6
6
  } from './ai-agent-settings.ts';
7
7
 
8
+ import {agentRequest, desktopAgentError, desktopAgentText, type DesktopAgent, type DesktopAiAgentsPort} from './desktop-ai-agents.ts';
9
+
8
10
  export * from './ai-agent-settings.ts';
11
+ export type {DesktopAiAgentsPort} from './desktop-ai-agents.ts';
9
12
 
10
13
  export interface AiAgentsOptions {
11
14
  /** The workbench stylesheet's class names (`editor.css`), for the menu and the settings dialog. */
@@ -14,6 +17,7 @@ export interface AiAgentsOptions {
14
17
  storageKey?: string;
15
18
  /** Opens a service; defaults to a new browser tab. */
16
19
  open?: Opener;
20
+ desktop?: DesktopAiAgentsPort | null;
17
21
  }
18
22
 
19
23
  /**
@@ -21,8 +25,8 @@ export interface AiAgentsOptions {
21
25
  * its own entry for the dialog. Every part reads the saved settings when it opens.
22
26
  */
23
27
  export function createAiAgents(React, {styles = {}, storage = browserStorage(), storageKey = agentSettingsKey,
24
- open}: AiAgentsOptions = {}) {
25
- const {createElement: element, useRef, useState} = React;
28
+ open = (...args) => window.open(...args), desktop}: AiAgentsOptions = {}) {
29
+ const {createElement: element, useEffect, useRef, useState} = React;
26
30
  const svg = (...children) => element('svg', {
27
31
  'aria-hidden': true, focusable: false, width: 16, height: 16, viewBox: '0 0 16 16',
28
32
  fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round'
@@ -34,8 +38,8 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
34
38
  G: 'M9.9 5.6A2.4 2.4 0 1 0 10.4 7H8.4'
35
39
  };
36
40
  /** A plain chat bubble with the service's initial for a preset; a globe for the user's own address. */
37
- const serviceIcon = (service: AgentService) => {
38
- const preset = agentPresets.find(item => item.id === service.preset);
41
+ const serviceIcon = (service?: AgentService) => {
42
+ const preset = agentPresets.find(item => item.id === service?.preset);
39
43
  if (preset) {
40
44
  const svgElement = svg(element('path', {d: bubble}), element('path', {d: initials[preset.letter]}));
41
45
  return React.cloneElement(svgElement, {'data-initial': preset.letter});
@@ -44,11 +48,30 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
44
48
  };
45
49
  const settingsIcon = () => svg(element('path', {d: agentsIconPath}));
46
50
 
47
- const openSettings = ({locale, returnFocus}: {locale: string; returnFocus?: HTMLElement | null}) =>
48
- openAgentSettingsDialog({document, locale, styles, storage, storageKey, returnFocus});
51
+ const openSettings = ({locale, returnFocus, onSave, onDesktopSave}: {
52
+ locale: string; returnFocus?: HTMLElement | null; onSave?: () => void; onDesktopSave?: () => void;
53
+ }) => openAgentSettingsDialog({document: returnFocus?.ownerDocument ?? document, locale, styles, storage,
54
+ storageKey, returnFocus, onSave, desktop, onDesktopSave});
49
55
 
50
- function AgentMenu({locale, close}: DrawerMenuRenderProps) {
51
- const [services] = useState(() => enabledAgentServices(readAgentSettings(storage, storageKey)));
56
+ function AgentList({locale, close}: Omit<DrawerMenuRenderProps, 'close'> & {close?: () => void}) {
57
+ const [services, setServices] = useState(() => enabledAgentServices(readAgentSettings(storage, storageKey)));
58
+ const [applications, setApplications] = useState([] as DesktopAgent[]);
59
+ const [error, setError] = useState(null as {code: string; url?: string} | null);
60
+ const active = useRef(true);
61
+ const refreshApplications = async () => {
62
+ if (!desktop) return;
63
+ const result = await agentRequest(() => desktop.list());
64
+ if (!active.current) return;
65
+ if ('value' in result) {
66
+ setApplications(result.value.entries);
67
+ setError(null);
68
+ } else setError({code: result.code});
69
+ };
70
+ useEffect(() => {
71
+ active.current = true;
72
+ void refreshApplications();
73
+ return () => { active.current = false; };
74
+ }, []);
52
75
  const list = useRef(null);
53
76
  const hintId = useRef(null);
54
77
  if (!hintId.current) hintId.current = `plus-agent-menu-hint-${++nextId}`;
@@ -67,29 +90,52 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
67
90
  items[next]?.focus();
68
91
  };
69
92
  const item = (key: string, icon, text: string, onClick: () => void, title?: string) => element('button', {
70
- key, type: 'button', role: 'menuitem', tabIndex: -1, className: styles.aiAgentMenuItem, title, onClick
93
+ key, type: 'button', role: close ? 'menuitem' : undefined, tabIndex: close ? -1 : undefined, className: styles.aiAgentMenuItem, title, onClick
71
94
  }, icon, element('span', null, text));
95
+ const hasEntries = services.length + applications.length > 0;
96
+ const launch = async (application: DesktopAgent) => {
97
+ setError(null);
98
+ const result = await agentRequest(() => desktop.launch(application.id));
99
+ if (!active.current) return;
100
+ if ('value' in result) close?.();
101
+ else {
102
+ const checked = checkAgentUrl(application.url);
103
+ setError({code: result.code, ...('url' in checked ? checked : {})});
104
+ }
105
+ };
72
106
  return element(React.Fragment, null,
73
- !services.length && element('p', {id: hintId.current, className: styles.aiAgentMenuHint}, agentText('empty', locale)),
107
+ error && element('p', {role: 'alert', className: styles.aiAgentMenuHint}, desktopAgentError(error.code, locale)),
108
+ !hasEntries && element('p', {id: hintId.current, className: styles.aiAgentMenuHint}, agentText('empty', locale)),
74
109
  element('div', {
75
- role: 'menu', 'aria-label': label, ref: list, className: styles.aiAgentMenu, onKeyDown: move,
76
- 'aria-describedby': services.length ? undefined : hintId.current
110
+ role: close ? 'menu' : 'group', 'aria-label': label, ref: list, className: styles.aiAgentMenu,
111
+ onKeyDown: close ? move : undefined,
112
+ 'aria-describedby': hasEntries ? undefined : hintId.current
77
113
  },
78
114
  services.map(service => item(service.id, serviceIcon(service), service.name, () => {
79
115
  openAgentService(service, open);
80
- close();
116
+ close?.();
81
117
  }, newTab)),
82
- services.length > 0 && element('div', {role: 'separator', className: styles.aiAgentMenuSeparator}),
118
+ applications.map(application => item(`desktop-${application.id}`, settingsIcon(), application.name,
119
+ () => void launch(application), desktopAgentText('opensApp', locale))),
120
+ error?.url && item('fallback', serviceIcon(), desktopAgentText('openFallback', locale), () => {
121
+ open(error.url, '_blank', 'noopener,noreferrer');
122
+ close?.();
123
+ }, newTab),
124
+ hasEntries && element('div', {role: 'separator', className: styles.aiAgentMenuSeparator}),
83
125
  item('settings', settingsIcon(), agentText('settings', locale), () => {
84
- close();
85
- openSettings({locale, returnFocus: document.activeElement as HTMLElement});
126
+ const doc = list.current.ownerDocument;
127
+ close?.();
128
+ openSettings({locale, returnFocus: doc.activeElement as HTMLElement,
129
+ onSave: close ? undefined : () => setServices(enabledAgentServices(readAgentSettings(storage, storageKey))),
130
+ onDesktopSave: close ? undefined : () => { void refreshApplications(); }});
86
131
  })));
87
132
  }
88
133
 
89
134
  const drawerMenu: DrawerMenu = {
90
- renderMenu: props => element(AgentMenu, props)
135
+ renderMenu: props => element(AgentList, props)
91
136
  };
92
- return {drawerMenu, openSettings, settingsIcon, serviceIcon};
137
+ return {drawerMenu, renderPanel: ({locale}: {locale: string}) => element(AgentList, {locale}),
138
+ openSettings, settingsIcon, serviceIcon};
93
139
  }
94
140
 
95
141
  let nextId = 0;