@kubohiroya/turbowarp-plus-editor-workbench 0.8.0 → 0.10.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.
package/README.ja.md CHANGED
@@ -66,6 +66,7 @@ const aiAgents = createAiAgents(React, {styles});
66
66
  aiAgents.openSettings({locale, returnFocus: trigger});
67
67
  ```
68
68
 
69
+ - Desktop のホストは `createAiAgents(React, {styles, desktop})` に `DesktopAiAgentsPort` を渡す。OS のアプリ選択、確認、設定の保存はホストが担当する。メニューと「試しに起動」は保存済み項目の ID を渡す。Web の設定を保存する際は、読み取った未知の起動種別の項目も保持する。
69
70
  - メニューは、メニューに出すことにしたサービスを、アイコンと名前で並べ、区切りのあとに「AI エージェント設定…」を置く。出すサービスがないときは、その項目と短い案内だけを出す。矢印キー、Home、End で項目を移る。サービスを選ぶと、`window.open(url, '_blank', 'noopener,noreferrer')` で開く。
70
71
  - 用意されたサービスは ChatGPT(`https://chatgpt.com/`)と Claude(`https://claude.ai/new`)。それぞれメニューから外せ、以前の会話などの URL に置き換えられる。URL を空にすると既定に戻る。利用者は、名前と URL で自分のサービスを足し、消せる。URL は `https:` で始まるものだけを受け付け、ほかは欄の下に誤りを出す。アイコンは汎用のもので、用意されたサービスは頭文字入りの吹き出し、自分のサービスは地球儀にする。各サービスのロゴは使わない。
71
72
  - ダイアログ(`role="dialog"`、`aria-modal`)は React を使わない DOM で、`openAgentSettingsDialog` で開ける。開くと最初の欄に移り、Tab はダイアログの中を回る。Escape かキャンセルで保存せずに閉じ、`returnFocus`、なければ開く前の要素に戻る。
package/README.md CHANGED
@@ -68,6 +68,7 @@ const aiAgents = createAiAgents(React, {styles});
68
68
  aiAgents.openSettings({locale, returnFocus: trigger});
69
69
  ```
70
70
 
71
+ - A Desktop host can pass a `DesktopAiAgentsPort` to `createAiAgents(React, {styles, desktop})`. The host owns native app selection, confirmations and persistence. The menu and test launch pass only the saved entry's ID. Saving web settings preserves entries with unknown target kinds.
71
72
  - The menu lists the turned-on services, each with an icon and its name, then a separator and "AI エージェント設定…" / "AI agent settings…". Without turned-on services it shows only that item and a short hint. Arrow keys, Home and End move between the items. Choosing a service opens its address with `window.open(url, '_blank', 'noopener,noreferrer')`.
72
73
  - The presets are ChatGPT (`https://chatgpt.com/`) and Claude (`https://claude.ai/new`). Each can be turned off, and its address replaced by a deep link such as a previous conversation; an empty address means the default. The user can add and remove services of their own (name and address). Only `https:` addresses are accepted; anything else shows an error under the field. The icons are generic: a chat bubble with an initial for a preset, a globe for the user's own service. No service logos are used.
73
74
  - The dialog (`role="dialog"`, `aria-modal`) is plain DOM, so it can be opened without React (`openAgentSettingsDialog`). It focuses its first field, keeps Tab inside, closes on Escape or Cancel without saving, and returns focus to `returnFocus` or to the element focused before.
@@ -1,8 +1,8 @@
1
+ import { type DesktopAiAgentsPort } from './desktop-ai-agents.ts';
1
2
  /** The services the Editor knows by name. Their name and icon are fixed; their address can be replaced. */
2
3
  export type AgentPresetId = 'chatgpt' | 'claude';
3
4
  /**
4
- * Where a service is opened. Only web pages for now; a desktop app launched with arguments is planned
5
- * as another `kind`, which this version ignores when it reads the settings.
5
+ * A web service. Desktop applications are stored separately by the Desktop host.
6
6
  */
7
7
  export interface AgentUrlTarget {
8
8
  kind: 'url';
@@ -21,6 +21,7 @@ export interface AgentSettings {
21
21
  version: 1;
22
22
  /** The presets in their fixed order, then the user's own services. */
23
23
  services: AgentService[];
24
+ unknownServices?: unknown[];
24
25
  }
25
26
  export type AgentStorage = Pick<Storage, 'getItem' | 'setItem'>;
26
27
  export declare const agentSettingsKey = "twPlusAiAgents";
@@ -38,7 +39,7 @@ export declare function checkAgentUrl(value: unknown): {
38
39
  problem: AgentUrlProblem;
39
40
  };
40
41
  export declare const defaultAgentSettings: () => AgentSettings;
41
- /** Settings read from saved JSON. Anything missing, unknown or invalid falls back to the defaults, entry by entry. */
42
+ /** Reads usable web services and preserves settings for target kinds this version cannot open. */
42
43
  export declare function parseAgentSettings(raw: string | null | undefined): AgentSettings;
43
44
  export declare const browserStorage: () => AgentStorage | null;
44
45
  export declare function readAgentSettings(storage?: AgentStorage | null, key?: string): AgentSettings;
@@ -73,7 +74,7 @@ declare const texts: {
73
74
  readonly urlNotHttps: readonly ["https: で始まるアドレスだけを使えます。", "Only addresses that start with https: can be used."];
74
75
  readonly saveFailed: readonly ["設定を保存できませんでした。ブラウザーの保存領域が使えません。", "The settings could not be saved: browser storage is unavailable."];
75
76
  };
76
- export declare const agentText: (key: keyof typeof texts, locale: string) => "AI エージェント" | "AI agents" | "AI エージェント設定…" | "AI agent settings…" | "メニューに出す AI サービスがありません。設定で選んでください。" | "No AI services are shown here. Choose them in the settings." | "別のタブで開きます" | "Opens in a new tab" | "AI エージェント設定" | "AI agent settings" | "ドロワーの AI エージェントのメニューに出すサービスを選びます。URL は、以前の会話など https: で始まるアドレスに置き換えられます。" | "Choose the services the AI agent menu in the drawer shows. Each URL can be replaced by any https: address, such as a previous conversation." | "用意されたサービス" | "Built-in services" | "追加したサービス" | "Your services" | "まだありません。" | "None yet." | "Service" | "メニューに出す" | "Show in the menu" | "名前" | "Name" | "URL" | "空欄のときは" | "When empty:" | "サービスを追加" | "Add a service" | "削除" | "Remove" | "キャンセル" | "Cancel" | "保存" | "Save" | "名前を入力してください。" | "Enter a name." | "URL を入力してください。" | "Enter a URL." | "URL として読めません。https: で始まるアドレスを入力してください。" | "This is not a URL. Enter an address that starts with https:." | "https: で始まるアドレスだけを使えます。" | "Only addresses that start with https: can be used." | "設定を保存できませんでした。ブラウザーの保存領域が使えません。" | "The settings could not be saved: browser storage is unavailable.";
77
+ export declare const agentText: (key: keyof typeof texts, locale: string) => "AI エージェント" | "AI agents" | "Name" | "名前" | "AI エージェント設定…" | "AI agent settings…" | "メニューに出す AI サービスがありません。設定で選んでください。" | "No AI services are shown here. Choose them in the settings." | "別のタブで開きます" | "Opens in a new tab" | "AI エージェント設定" | "AI agent settings" | "ドロワーの AI エージェントのメニューに出すサービスを選びます。URL は、以前の会話など https: で始まるアドレスに置き換えられます。" | "Choose the services the AI agent menu in the drawer shows. Each URL can be replaced by any https: address, such as a previous conversation." | "用意されたサービス" | "Built-in services" | "追加したサービス" | "Your services" | "まだありません。" | "None yet." | "Service" | "メニューに出す" | "Show in the menu" | "URL" | "空欄のときは" | "When empty:" | "サービスを追加" | "Add a service" | "削除" | "Remove" | "キャンセル" | "Cancel" | "保存" | "Save" | "名前を入力してください。" | "Enter a name." | "URL を入力してください。" | "Enter a URL." | "URL として読めません。https: で始まるアドレスを入力してください。" | "This is not a URL. Enter an address that starts with https:." | "https: で始まるアドレスだけを使えます。" | "Only addresses that start with https: can be used." | "設定を保存できませんでした。ブラウザーの保存領域が使えません。" | "The settings could not be saved: browser storage is unavailable.";
77
78
  export interface AgentSettingsDialogOptions {
78
79
  document?: Document;
79
80
  locale: string;
@@ -84,6 +85,7 @@ export interface AgentSettingsDialogOptions {
84
85
  /** Where focus goes when the dialog closes. Defaults to the element focused when it opened. */
85
86
  returnFocus?: HTMLElement | null;
86
87
  onSave?(settings: AgentSettings): void;
88
+ desktop?: DesktopAiAgentsPort | null;
87
89
  }
88
90
  export interface AgentSettingsDialog {
89
91
  element: HTMLElement;
@@ -93,5 +95,5 @@ export interface AgentSettingsDialog {
93
95
  * The settings dialog: turns the presets on and off, replaces their address, and adds or removes the
94
96
  * user's own services. It is plain DOM so that any part of the Editor can open it, with or without React.
95
97
  */
96
- export declare function openAgentSettingsDialog({ document: doc, locale, styles, storage, storageKey, returnFocus, onSave }: AgentSettingsDialogOptions): AgentSettingsDialog;
98
+ export declare function openAgentSettingsDialog({ document: doc, locale, styles, storage, storageKey, returnFocus, onSave, desktop }: AgentSettingsDialogOptions): AgentSettingsDialog;
97
99
  export {};
@@ -1,4 +1,5 @@
1
1
  import { isJapanese } from "./drawer-views.js";
2
+ import { desktopAgentSettings } from "./desktop-ai-agents.js";
2
3
  export const agentSettingsKey = 'twPlusAiAgents';
3
4
  export const agentPresets = [
4
5
  { id: 'chatgpt', name: 'ChatGPT', url: 'https://chatgpt.com/', letter: 'G' },
@@ -31,7 +32,7 @@ const presetService = (preset, saved) => {
31
32
  };
32
33
  };
33
34
  export const defaultAgentSettings = () => ({ version: 1, services: agentPresets.map(preset => presetService(preset)) });
34
- /** Settings read from saved JSON. Anything missing, unknown or invalid falls back to the defaults, entry by entry. */
35
+ /** Reads usable web services and preserves settings for target kinds this version cannot open. */
35
36
  export function parseAgentSettings(raw) {
36
37
  let saved;
37
38
  try {
@@ -44,9 +45,11 @@ export function parseAgentSettings(raw) {
44
45
  !Array.isArray(saved.services))
45
46
  return defaultAgentSettings();
46
47
  const entries = saved.services.filter(entry => entry && typeof entry === 'object');
47
- const presets = agentPresets.map(preset => presetService(preset, entries.find(entry => entry.preset === preset.id)));
48
+ const presets = agentPresets.map(preset => presetService(preset, entries.find(entry => entry.preset === preset.id &&
49
+ (entry.target?.kind === 'url' || entry.target?.kind === undefined))));
48
50
  const ids = new Set(presets.map(service => service.id));
49
51
  const custom = [];
52
+ const unknownServices = entries.filter(entry => typeof entry.target?.kind === 'string' && entry.target.kind !== 'url');
50
53
  for (const entry of entries) {
51
54
  if (entry.preset !== undefined || entry.target?.kind !== 'url')
52
55
  continue;
@@ -60,7 +63,7 @@ export function parseAgentSettings(raw) {
60
63
  ids.add(id);
61
64
  custom.push({ id, name, enabled: entry.enabled !== false, target: { kind: 'url', url: checked.url } });
62
65
  }
63
- return { version: 1, services: [...presets, ...custom] };
66
+ return { version: 1, services: [...presets, ...custom], ...(unknownServices.length ? { unknownServices } : {}) };
64
67
  }
65
68
  export const browserStorage = () => {
66
69
  try {
@@ -83,9 +86,9 @@ export function writeAgentSettings(settings, storage = browserStorage(), key = a
83
86
  if (!storage)
84
87
  return false;
85
88
  try {
86
- storage.setItem(key, JSON.stringify({ version: 1, services: settings.services.map(service => service.preset ?
87
- { preset: service.preset, enabled: service.enabled, target: service.target } :
88
- { id: service.id, name: service.name, enabled: service.enabled, target: service.target }) }));
89
+ storage.setItem(key, JSON.stringify({ version: 1, services: [...settings.services.map(service => service.preset ?
90
+ { preset: service.preset, enabled: service.enabled, target: service.target } :
91
+ { id: service.id, name: service.name, enabled: service.enabled, target: service.target }), ...(settings.unknownServices ?? [])] }));
89
92
  return true;
90
93
  }
91
94
  catch {
@@ -128,13 +131,13 @@ const texts = {
128
131
  export const agentText = (key, locale) => texts[key][isJapanese(locale) ? 0 : 1];
129
132
  let openDialog = null;
130
133
  let nextDialog = 0;
131
- const focusable = 'button:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
134
+ const focusable = 'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
132
135
  const urlProblems = { empty: 'urlEmpty', invalid: 'urlInvalid', 'not-https': 'urlNotHttps' };
133
136
  /**
134
137
  * The settings dialog: turns the presets on and off, replaces their address, and adds or removes the
135
138
  * user's own services. It is plain DOM so that any part of the Editor can open it, with or without React.
136
139
  */
137
- export function openAgentSettingsDialog({ document: doc = globalThis.document, locale, styles = {}, storage = browserStorage(), storageKey = agentSettingsKey, returnFocus, onSave }) {
140
+ export function openAgentSettingsDialog({ document: doc = globalThis.document, locale, styles = {}, storage = browserStorage(), storageKey = agentSettingsKey, returnFocus, onSave, desktop }) {
138
141
  if (openDialog?.element.isConnected) {
139
142
  openDialog.element.querySelector(focusable)?.focus();
140
143
  return openDialog;
@@ -232,7 +235,7 @@ export function openAgentSettingsDialog({ document: doc = globalThis.document, l
232
235
  const status = make('p', { role: 'alert', class: styles.aiAgentDialogError, hidden: '' });
233
236
  const cancel = make('button', { type: 'button', class: styles.aiAgentDialogButton }, text('cancel'));
234
237
  const save = make('button', { type: 'submit', class: `${styles.aiAgentDialogButton ?? ''} ${styles.aiAgentDialogPrimary ?? ''}`.trim() }, text('save'));
235
- const form = make('form', { novalidate: '', class: styles.aiAgentDialogForm }, presetGroup, customGroup, status, make('div', { class: styles.aiAgentDialogActions }, cancel, save));
238
+ const form = make('form', { novalidate: '', class: styles.aiAgentDialogForm }, presetGroup, customGroup, desktop && desktopAgentSettings(doc, desktop, locale, styles), status, make('div', { class: styles.aiAgentDialogActions }, cancel, save));
236
239
  const element = make('div', {
237
240
  role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': `${prefix}-title`,
238
241
  'aria-describedby': `${prefix}-description`, class: styles.aiAgentDialog
@@ -257,7 +260,7 @@ export function openAgentSettingsDialog({ document: doc = globalThis.document, l
257
260
  }
258
261
  if (event.key !== 'Tab')
259
262
  return;
260
- const items = [...element.querySelectorAll(focusable)];
263
+ const items = [...element.querySelectorAll(focusable)].filter(item => !item.matches(':disabled'));
261
264
  const first = items[0];
262
265
  const last = items[items.length - 1];
263
266
  if (event.shiftKey && doc.activeElement === first) {
@@ -300,7 +303,7 @@ export function openAgentSettingsDialog({ document: doc = globalThis.document, l
300
303
  for (const service of services)
301
304
  if (!service.preset)
302
305
  service.id = `custom-${++count}`;
303
- const saved = { version: 1, services };
306
+ const saved = { ...settings, services };
304
307
  if (!writeAgentSettings(saved, storage, storageKey)) {
305
308
  status.textContent = text('saveFailed');
306
309
  status.hidden = false;
@@ -1,6 +1,8 @@
1
1
  import type { DrawerMenu } from './drawer-views.ts';
2
2
  import { type AgentService, type AgentStorage, type Opener } from './ai-agent-settings.ts';
3
+ import { type DesktopAiAgentsPort } from './desktop-ai-agents.ts';
3
4
  export * from './ai-agent-settings.ts';
5
+ export type { DesktopAiAgentsPort } from './desktop-ai-agents.ts';
4
6
  export interface AiAgentsOptions {
5
7
  /** The workbench stylesheet's class names (`editor.css`), for the menu and the settings dialog. */
6
8
  styles?: Record<string, string>;
@@ -8,17 +10,18 @@ export interface AiAgentsOptions {
8
10
  storageKey?: string;
9
11
  /** Opens a service; defaults to a new browser tab. */
10
12
  open?: Opener;
13
+ desktop?: DesktopAiAgentsPort | null;
11
14
  }
12
15
  /**
13
16
  * The AI agent menu for `drawerViews.agents`, the settings dialog and the icon the host shows beside
14
17
  * its own entry for the dialog. Every part reads the saved settings when it opens.
15
18
  */
16
- export declare function createAiAgents(React: any, { styles, storage, storageKey, open }?: AiAgentsOptions): {
19
+ export declare function createAiAgents(React: any, { styles, storage, storageKey, open, desktop }?: AiAgentsOptions): {
17
20
  drawerMenu: DrawerMenu;
18
21
  openSettings: ({ locale, returnFocus }: {
19
22
  locale: string;
20
23
  returnFocus?: HTMLElement | null;
21
24
  }) => import("./ai-agent-settings.ts").AgentSettingsDialog;
22
25
  settingsIcon: () => any;
23
- serviceIcon: (service: AgentService) => any;
26
+ serviceIcon: (service?: AgentService) => any;
24
27
  };
package/dist/ai-agents.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { agentsIconPath } from "./drawer-views.js";
2
- import { agentPresets, agentSettingsKey, agentText, browserStorage, enabledAgentServices, openAgentService, openAgentSettingsDialog, readAgentSettings } from "./ai-agent-settings.js";
2
+ import { agentPresets, agentSettingsKey, agentText, browserStorage, checkAgentUrl, enabledAgentServices, openAgentService, openAgentSettingsDialog, readAgentSettings } from "./ai-agent-settings.js";
3
+ import { agentRequest, desktopAgentError, desktopAgentText } from "./desktop-ai-agents.js";
3
4
  export * from "./ai-agent-settings.js";
4
5
  /**
5
6
  * The AI agent menu for `drawerViews.agents`, the settings dialog and the icon the host shows beside
6
7
  * its own entry for the dialog. Every part reads the saved settings when it opens.
7
8
  */
8
- export function createAiAgents(React, { styles = {}, storage = browserStorage(), storageKey = agentSettingsKey, open } = {}) {
9
- const { createElement: element, useRef, useState } = React;
9
+ export function createAiAgents(React, { styles = {}, storage = browserStorage(), storageKey = agentSettingsKey, open = (...args) => window.open(...args), desktop } = {}) {
10
+ const { createElement: element, useEffect, useRef, useState } = React;
10
11
  const svg = (...children) => element('svg', {
11
12
  'aria-hidden': true, focusable: false, width: 16, height: 16, viewBox: '0 0 16 16',
12
13
  fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round'
@@ -19,7 +20,7 @@ export function createAiAgents(React, { styles = {}, storage = browserStorage(),
19
20
  };
20
21
  /** A plain chat bubble with the service's initial for a preset; a globe for the user's own address. */
21
22
  const serviceIcon = (service) => {
22
- const preset = agentPresets.find(item => item.id === service.preset);
23
+ const preset = agentPresets.find(item => item.id === service?.preset);
23
24
  if (preset) {
24
25
  const svgElement = svg(element('path', { d: bubble }), element('path', { d: initials[preset.letter] }));
25
26
  return React.cloneElement(svgElement, { 'data-initial': preset.letter });
@@ -27,9 +28,25 @@ export function createAiAgents(React, { styles = {}, storage = browserStorage(),
27
28
  return svg(element('circle', { cx: 8, cy: 8, r: 6.25 }), element('path', { d: 'M1.75 8h12.5M8 1.75c-3 3.4-3 9.1 0 12.5M8 1.75c3 3.4 3 9.1 0 12.5' }));
28
29
  };
29
30
  const settingsIcon = () => svg(element('path', { d: agentsIconPath }));
30
- const openSettings = ({ locale, returnFocus }) => openAgentSettingsDialog({ document, locale, styles, storage, storageKey, returnFocus });
31
+ const openSettings = ({ locale, returnFocus }) => openAgentSettingsDialog({ document, locale, styles, storage, storageKey, returnFocus, desktop });
31
32
  function AgentMenu({ locale, close }) {
32
33
  const [services] = useState(() => enabledAgentServices(readAgentSettings(storage, storageKey)));
34
+ const [applications, setApplications] = useState([]);
35
+ const [error, setError] = useState(null);
36
+ const active = useRef(true);
37
+ useEffect(() => {
38
+ active.current = true;
39
+ if (desktop)
40
+ void agentRequest(() => desktop.list()).then(result => {
41
+ if (!active.current)
42
+ return;
43
+ if ('value' in result)
44
+ setApplications(result.value.entries);
45
+ else
46
+ setError({ code: result.code });
47
+ });
48
+ return () => { active.current = false; };
49
+ }, []);
33
50
  const list = useRef(null);
34
51
  const hintId = useRef(null);
35
52
  if (!hintId.current)
@@ -56,13 +73,29 @@ export function createAiAgents(React, { styles = {}, storage = browserStorage(),
56
73
  const item = (key, icon, text, onClick, title) => element('button', {
57
74
  key, type: 'button', role: 'menuitem', tabIndex: -1, className: styles.aiAgentMenuItem, title, onClick
58
75
  }, icon, element('span', null, text));
59
- return element(React.Fragment, null, !services.length && element('p', { id: hintId.current, className: styles.aiAgentMenuHint }, agentText('empty', locale)), element('div', {
76
+ const hasEntries = services.length + applications.length > 0;
77
+ const launch = async (application) => {
78
+ setError(null);
79
+ const result = await agentRequest(() => desktop.launch(application.id));
80
+ if (!active.current)
81
+ return;
82
+ if ('value' in result)
83
+ close();
84
+ else {
85
+ const checked = checkAgentUrl(application.url);
86
+ setError({ code: result.code, ...('url' in checked ? checked : {}) });
87
+ }
88
+ };
89
+ return element(React.Fragment, null, error && element('p', { role: 'alert', className: styles.aiAgentMenuHint }, desktopAgentError(error.code, locale)), !hasEntries && element('p', { id: hintId.current, className: styles.aiAgentMenuHint }, agentText('empty', locale)), element('div', {
60
90
  role: 'menu', 'aria-label': label, ref: list, className: styles.aiAgentMenu, onKeyDown: move,
61
- 'aria-describedby': services.length ? undefined : hintId.current
91
+ 'aria-describedby': hasEntries ? undefined : hintId.current
62
92
  }, services.map(service => item(service.id, serviceIcon(service), service.name, () => {
63
93
  openAgentService(service, open);
64
94
  close();
65
- }, newTab)), services.length > 0 && element('div', { role: 'separator', className: styles.aiAgentMenuSeparator }), item('settings', settingsIcon(), agentText('settings', locale), () => {
95
+ }, newTab)), applications.map(application => item(`desktop-${application.id}`, settingsIcon(), application.name, () => void launch(application), desktopAgentText('opensApp', locale))), error?.url && item('fallback', serviceIcon(), desktopAgentText('openFallback', locale), () => {
96
+ open(error.url, '_blank', 'noopener,noreferrer');
97
+ close();
98
+ }, newTab), hasEntries && element('div', { role: 'separator', className: styles.aiAgentMenuSeparator }), item('settings', settingsIcon(), agentText('settings', locale), () => {
66
99
  close();
67
100
  openSettings({ locale, returnFocus: document.activeElement });
68
101
  })));
@@ -0,0 +1,80 @@
1
+ export interface DesktopAgentDraft {
2
+ id: string;
3
+ name: string;
4
+ args: string[];
5
+ cwd: string;
6
+ selection?: string;
7
+ url?: string;
8
+ }
9
+ export interface DesktopAgent extends DesktopAgentDraft {
10
+ application: string;
11
+ }
12
+ type AgentContext = Record<'projectFolder' | 'repository' | 'branch', string | null>;
13
+ type AgentList = {
14
+ revision: string | null;
15
+ entries: DesktopAgent[];
16
+ };
17
+ type Result<T> = {
18
+ ok: true;
19
+ value: T;
20
+ } | {
21
+ ok: false;
22
+ code: string;
23
+ };
24
+ /** The Desktop host owns the executable paths, confirmations and launch settings. */
25
+ export interface DesktopAiAgentsPort {
26
+ list(): Promise<Result<AgentList>>;
27
+ context(): Promise<Result<AgentContext>>;
28
+ chooseContext(kind: 'project' | 'repository'): Promise<Result<AgentContext | null>>;
29
+ chooseApp(): Promise<Result<{
30
+ selection: string;
31
+ application: string;
32
+ } | null>>;
33
+ save(revision: string | null, entries: DesktopAgentDraft[]): Promise<Result<AgentList>>;
34
+ launch(id: string): Promise<Result<null>>;
35
+ }
36
+ declare const strings: {
37
+ readonly section: readonly ["Desktop applications", "デスクトップアプリ"];
38
+ readonly opensApp: readonly ["Launches a desktop application", "デスクトップアプリを起動します"];
39
+ readonly add: readonly ["Add an application", "アプリを追加"];
40
+ readonly name: readonly ["Name", "名前"];
41
+ readonly application: readonly ["Application", "アプリ"];
42
+ readonly choose: readonly ["Choose…", "選択…"];
43
+ readonly unselected: readonly ["No application selected", "アプリが選択されていません"];
44
+ readonly args: readonly ["Arguments (one per line)", "引数(1 行に 1 つ)"];
45
+ readonly cwd: readonly ["Working directory", "作業ディレクトリ"];
46
+ readonly url: readonly ["Fallback website (optional)", "代わりに開く Web サイト(任意)"];
47
+ readonly openFallback: readonly ["Open the website", "Web サイトを開く"];
48
+ readonly 'invalid-url': readonly ["Enter an HTTPS address for the fallback website.", "代わりに開く Web サイトには HTTPS の URL を入力してください。"];
49
+ readonly variables: readonly ["Available placeholders: {projectFolder}, {repository}, {branch}.", "使える置き換えは {projectFolder}・{repository}・{branch} です。"];
50
+ readonly chooseProject: readonly ["Choose project folder…", "プロジェクトフォルダを選択…"];
51
+ readonly chooseRepository: readonly ["Choose Git repository…", "Git リポジトリを選択…"];
52
+ readonly projectFolder: readonly ["Project folder", "プロジェクトフォルダ"];
53
+ readonly repository: readonly ["Git repository", "Git リポジトリ"];
54
+ readonly branch: readonly ["Branch", "ブランチ"];
55
+ readonly preview: readonly ["Expanded arguments", "置き換え後の引数"];
56
+ readonly up: readonly ["Move up", "上へ移動"];
57
+ readonly down: readonly ["Move down", "下へ移動"];
58
+ readonly remove: readonly ["Remove application", "アプリを削除"];
59
+ readonly save: readonly ["Save applications", "アプリの設定を保存"];
60
+ readonly saved: readonly ["Application settings saved.", "アプリの設定を保存しました。"];
61
+ readonly test: readonly ["Try launching", "試しに起動"];
62
+ readonly saveFirst: readonly ["Save the application before trying it.", "試しに起動するには、先にアプリの設定を保存してください。"];
63
+ readonly launched: readonly ["Launch requested.", "アプリを起動しました。"];
64
+ readonly invalid: readonly ["Enter a name and choose an application for each entry.", "各項目の名前を入力し、アプリを選択してください。"];
65
+ readonly conflict: readonly ["The application settings changed. Reopen the settings and try again.", "アプリの設定が変更されました。設定を開き直してからやり直してください。"];
66
+ readonly busy: readonly ["Another application operation is in progress.", "別のアプリ操作を実行中です。"];
67
+ readonly cancelled: readonly ["The operation was cancelled.", "操作をキャンセルしました。"];
68
+ readonly unknown: readonly ["This application is no longer registered.", "このアプリは登録されていません。"];
69
+ readonly 'missing-context': readonly ["Choose the folder or repository used by the launch arguments. A branch is required for {branch}.", "引数で使うフォルダまたはリポジトリを選択してください。{branch} にはブランチが必要です。"];
70
+ readonly 'invalid-directory': readonly ["The working directory is unavailable.", "作業ディレクトリを利用できません。"];
71
+ readonly 'app-missing': readonly ["The selected application is missing or cannot run.", "選択したアプリが見つからないか、起動できません。"];
72
+ readonly 'launch-failed': readonly ["The application could not start.", "アプリを起動できませんでした。"];
73
+ readonly unavailable: readonly ["Desktop application settings are unavailable.", "デスクトップアプリの設定を利用できません。"];
74
+ };
75
+ export declare const desktopAgentText: (key: keyof typeof strings, locale: string) => "プロジェクトフォルダ" | "Project folder" | "Desktop applications" | "デスクトップアプリ" | "Launches a desktop application" | "デスクトップアプリを起動します" | "Add an application" | "アプリを追加" | "Name" | "名前" | "Application" | "アプリ" | "Choose…" | "選択…" | "No application selected" | "アプリが選択されていません" | "Arguments (one per line)" | "引数(1 行に 1 つ)" | "Working directory" | "作業ディレクトリ" | "Fallback website (optional)" | "代わりに開く Web サイト(任意)" | "Open the website" | "Web サイトを開く" | "Enter an HTTPS address for the fallback website." | "代わりに開く Web サイトには HTTPS の URL を入力してください。" | "Available placeholders: {projectFolder}, {repository}, {branch}." | "使える置き換えは {projectFolder}・{repository}・{branch} です。" | "Choose project folder…" | "プロジェクトフォルダを選択…" | "Choose Git repository…" | "Git リポジトリを選択…" | "Git repository" | "Git リポジトリ" | "Branch" | "ブランチ" | "Expanded arguments" | "置き換え後の引数" | "Move up" | "上へ移動" | "Move down" | "下へ移動" | "Remove application" | "アプリを削除" | "Save applications" | "アプリの設定を保存" | "Application settings saved." | "アプリの設定を保存しました。" | "Try launching" | "試しに起動" | "Save the application before trying it." | "試しに起動するには、先にアプリの設定を保存してください。" | "Launch requested." | "アプリを起動しました。" | "Enter a name and choose an application for each entry." | "各項目の名前を入力し、アプリを選択してください。" | "The application settings changed. Reopen the settings and try again." | "アプリの設定が変更されました。設定を開き直してからやり直してください。" | "Another application operation is in progress." | "別のアプリ操作を実行中です。" | "The operation was cancelled." | "操作をキャンセルしました。" | "This application is no longer registered." | "このアプリは登録されていません。" | "Choose the folder or repository used by the launch arguments. A branch is required for {branch}." | "引数で使うフォルダまたはリポジトリを選択してください。{branch} にはブランチが必要です。" | "The working directory is unavailable." | "作業ディレクトリを利用できません。" | "The selected application is missing or cannot run." | "選択したアプリが見つからないか、起動できません。" | "The application could not start." | "アプリを起動できませんでした。" | "Desktop application settings are unavailable." | "デスクトップアプリの設定を利用できません。";
76
+ export declare const desktopAgentError: (code: string, locale: string) => "プロジェクトフォルダ" | "Project folder" | "Desktop applications" | "デスクトップアプリ" | "Launches a desktop application" | "デスクトップアプリを起動します" | "Add an application" | "アプリを追加" | "Name" | "名前" | "Application" | "アプリ" | "Choose…" | "選択…" | "No application selected" | "アプリが選択されていません" | "Arguments (one per line)" | "引数(1 行に 1 つ)" | "Working directory" | "作業ディレクトリ" | "Fallback website (optional)" | "代わりに開く Web サイト(任意)" | "Open the website" | "Web サイトを開く" | "Enter an HTTPS address for the fallback website." | "代わりに開く Web サイトには HTTPS の URL を入力してください。" | "Available placeholders: {projectFolder}, {repository}, {branch}." | "使える置き換えは {projectFolder}・{repository}・{branch} です。" | "Choose project folder…" | "プロジェクトフォルダを選択…" | "Choose Git repository…" | "Git リポジトリを選択…" | "Git repository" | "Git リポジトリ" | "Branch" | "ブランチ" | "Expanded arguments" | "置き換え後の引数" | "Move up" | "上へ移動" | "Move down" | "下へ移動" | "Remove application" | "アプリを削除" | "Save applications" | "アプリの設定を保存" | "Application settings saved." | "アプリの設定を保存しました。" | "Try launching" | "試しに起動" | "Save the application before trying it." | "試しに起動するには、先にアプリの設定を保存してください。" | "Launch requested." | "アプリを起動しました。" | "Enter a name and choose an application for each entry." | "各項目の名前を入力し、アプリを選択してください。" | "The application settings changed. Reopen the settings and try again." | "アプリの設定が変更されました。設定を開き直してからやり直してください。" | "Another application operation is in progress." | "別のアプリ操作を実行中です。" | "The operation was cancelled." | "操作をキャンセルしました。" | "This application is no longer registered." | "このアプリは登録されていません。" | "Choose the folder or repository used by the launch arguments. A branch is required for {branch}." | "引数で使うフォルダまたはリポジトリを選択してください。{branch} にはブランチが必要です。" | "The working directory is unavailable." | "作業ディレクトリを利用できません。" | "The selected application is missing or cannot run." | "選択したアプリが見つからないか、起動できません。" | "The application could not start." | "アプリを起動できませんでした。" | "Desktop application settings are unavailable." | "デスクトップアプリの設定を利用できません。";
77
+ export declare function agentRequest<T>(request: () => Promise<Result<T>>): Promise<Result<T>>;
78
+ /** An optional section of the existing settings dialog. Its changes are saved by the Desktop host. */
79
+ export declare function desktopAgentSettings(doc: Document, port: DesktopAiAgentsPort, locale: string, styles: Record<string, string>): HTMLFieldSetElement;
80
+ export {};
@@ -0,0 +1,235 @@
1
+ import { isJapanese } from "./drawer-views.js";
2
+ const defaultDirectory = '{projectFolder}';
3
+ const variables = /\{(projectFolder|repository|branch)\}/gu;
4
+ const strings = {
5
+ section: ['Desktop applications', 'デスクトップアプリ'],
6
+ opensApp: ['Launches a desktop application', 'デスクトップアプリを起動します'],
7
+ add: ['Add an application', 'アプリを追加'],
8
+ name: ['Name', '名前'],
9
+ application: ['Application', 'アプリ'],
10
+ choose: ['Choose…', '選択…'],
11
+ unselected: ['No application selected', 'アプリが選択されていません'],
12
+ args: ['Arguments (one per line)', '引数(1 行に 1 つ)'],
13
+ cwd: ['Working directory', '作業ディレクトリ'],
14
+ url: ['Fallback website (optional)', '代わりに開く Web サイト(任意)'],
15
+ openFallback: ['Open the website', 'Web サイトを開く'],
16
+ 'invalid-url': ['Enter an HTTPS address for the fallback website.', '代わりに開く Web サイトには HTTPS の URL を入力してください。'],
17
+ variables: ['Available placeholders: {projectFolder}, {repository}, {branch}.', '使える置き換えは {projectFolder}・{repository}・{branch} です。'],
18
+ chooseProject: ['Choose project folder…', 'プロジェクトフォルダを選択…'],
19
+ chooseRepository: ['Choose Git repository…', 'Git リポジトリを選択…'],
20
+ projectFolder: ['Project folder', 'プロジェクトフォルダ'],
21
+ repository: ['Git repository', 'Git リポジトリ'],
22
+ branch: ['Branch', 'ブランチ'],
23
+ preview: ['Expanded arguments', '置き換え後の引数'],
24
+ up: ['Move up', '上へ移動'],
25
+ down: ['Move down', '下へ移動'],
26
+ remove: ['Remove application', 'アプリを削除'],
27
+ save: ['Save applications', 'アプリの設定を保存'],
28
+ saved: ['Application settings saved.', 'アプリの設定を保存しました。'],
29
+ test: ['Try launching', '試しに起動'],
30
+ saveFirst: ['Save the application before trying it.', '試しに起動するには、先にアプリの設定を保存してください。'],
31
+ launched: ['Launch requested.', 'アプリを起動しました。'],
32
+ invalid: ['Enter a name and choose an application for each entry.', '各項目の名前を入力し、アプリを選択してください。'],
33
+ conflict: ['The application settings changed. Reopen the settings and try again.', 'アプリの設定が変更されました。設定を開き直してからやり直してください。'],
34
+ busy: ['Another application operation is in progress.', '別のアプリ操作を実行中です。'],
35
+ cancelled: ['The operation was cancelled.', '操作をキャンセルしました。'],
36
+ unknown: ['This application is no longer registered.', 'このアプリは登録されていません。'],
37
+ 'missing-context': ['Choose the folder or repository used by the launch arguments. A branch is required for {branch}.',
38
+ '引数で使うフォルダまたはリポジトリを選択してください。{branch} にはブランチが必要です。'],
39
+ 'invalid-directory': ['The working directory is unavailable.', '作業ディレクトリを利用できません。'],
40
+ 'app-missing': ['The selected application is missing or cannot run.', '選択したアプリが見つからないか、起動できません。'],
41
+ 'launch-failed': ['The application could not start.', 'アプリを起動できませんでした。'],
42
+ unavailable: ['Desktop application settings are unavailable.', 'デスクトップアプリの設定を利用できません。']
43
+ };
44
+ export const desktopAgentText = (key, locale) => strings[key][isJapanese(locale) ? 1 : 0];
45
+ export const desktopAgentError = (code, locale) => desktopAgentText(Object.hasOwn(strings, code) ? code : 'unavailable', locale);
46
+ export async function agentRequest(request) {
47
+ try {
48
+ return await request();
49
+ }
50
+ catch {
51
+ return { ok: false, code: 'unavailable' };
52
+ }
53
+ }
54
+ /** An optional section of the existing settings dialog. Its changes are saved by the Desktop host. */
55
+ export function desktopAgentSettings(doc, port, locale, styles) {
56
+ const text = (key) => desktopAgentText(key, locale);
57
+ const make = (tag, className, content) => {
58
+ const node = doc.createElement(tag);
59
+ if (className)
60
+ node.className = className;
61
+ if (content)
62
+ node.textContent = content;
63
+ return node;
64
+ };
65
+ const button = (key, action) => {
66
+ const node = make('button', styles.aiAgentDialogButton, text(key));
67
+ node.type = 'button';
68
+ node.addEventListener('click', action);
69
+ return node;
70
+ };
71
+ const field = (key, input) => {
72
+ const label = make('label', styles.aiAgentDialogField, text(key));
73
+ label.append(input);
74
+ return label;
75
+ };
76
+ const list = make('div', styles.aiAgentDialogList);
77
+ const status = make('p', styles.aiAgentDialogNote);
78
+ status.setAttribute('role', 'status');
79
+ const section = make('fieldset', styles.aiAgentDialogSection);
80
+ let entries = [];
81
+ let saved = { revision: null, entries: [] };
82
+ let context = null;
83
+ const previews = new Map();
84
+ const run = async (request, done) => {
85
+ const focused = doc.activeElement;
86
+ section.disabled = true;
87
+ status.textContent = '';
88
+ const result = await agentRequest(request);
89
+ if (!section.isConnected)
90
+ return;
91
+ section.disabled = false;
92
+ if ('code' in result)
93
+ status.textContent = desktopAgentError(result.code, locale);
94
+ else
95
+ done(result.value);
96
+ if (doc.activeElement === doc.body && focused?.isConnected && section.contains(focused))
97
+ focused.focus();
98
+ };
99
+ const contextSummary = make('p', styles.aiAgentDialogNote);
100
+ contextSummary.style.overflowWrap = 'anywhere';
101
+ const refreshPreviews = () => {
102
+ contextSummary.textContent = ['projectFolder', 'repository', 'branch']
103
+ .map(key => `${text(key)} ${context?.[key] ?? '—'}`).join(' · ');
104
+ previews.forEach(render => render());
105
+ };
106
+ const chooseContext = (kind) => {
107
+ void run(() => port.chooseContext(kind), value => {
108
+ if (value)
109
+ context = value;
110
+ refreshPreviews();
111
+ });
112
+ };
113
+ const add = button('add', () => {
114
+ const entry = { id: globalThis.crypto.randomUUID(), name: '', application: '', args: [], cwd: defaultDirectory };
115
+ entries.push(entry);
116
+ render();
117
+ list.lastElementChild?.querySelector('input')?.focus();
118
+ });
119
+ const toDraft = ({ id, name, args, cwd, selection, url }) => ({ id, name, args, cwd, ...(selection ? { selection } : {}), ...(url?.trim() ? { url: url.trim() } : {}) });
120
+ const save = button('save', () => {
121
+ if (entries.some(entry => !entry.name.trim() || !entry.application)) {
122
+ status.textContent = text('invalid');
123
+ return;
124
+ }
125
+ void run(() => port.save(saved.revision, entries.map(toDraft)), value => {
126
+ saved = value;
127
+ entries = value.entries.map(entry => ({ ...entry }));
128
+ render();
129
+ status.textContent = text('saved');
130
+ });
131
+ });
132
+ function render() {
133
+ previews.clear();
134
+ list.replaceChildren();
135
+ for (const [index, entry] of entries.entries()) {
136
+ const row = make('div', styles.aiAgentDialogRow);
137
+ row.setAttribute('role', 'group');
138
+ row.setAttribute('aria-label', entry.name || text('application'));
139
+ const name = make('input');
140
+ name.maxLength = 120;
141
+ name.value = entry.name;
142
+ name.oninput = () => {
143
+ entry.name = name.value;
144
+ row.setAttribute('aria-label', entry.name || text('application'));
145
+ };
146
+ const application = make('p', styles.aiAgentDialogNote, entry.application || text('unselected'));
147
+ const choose = button('choose', () => {
148
+ void run(() => port.chooseApp(), value => {
149
+ if (value)
150
+ Object.assign(entry, value);
151
+ application.textContent = entry.application || text('unselected');
152
+ });
153
+ });
154
+ choose.setAttribute('aria-label', `${text('application')} ${text('choose')}`);
155
+ const args = make('textarea');
156
+ args.rows = 3;
157
+ args.value = entry.args.join('\n');
158
+ const cwd = make('input');
159
+ cwd.placeholder = defaultDirectory;
160
+ cwd.maxLength = 1024;
161
+ cwd.value = entry.cwd;
162
+ const url = make('input');
163
+ url.type = 'url';
164
+ url.maxLength = 2048;
165
+ url.value = entry.url ?? '';
166
+ url.oninput = () => { entry.url = url.value; };
167
+ const preview = make('p', styles.aiAgentDialogNote);
168
+ const updatePreview = () => {
169
+ const expand = (value) => value.replace(variables, (match, key) => context?.[key] ?? match);
170
+ const directory = (entry.cwd.trim() || defaultDirectory);
171
+ preview.textContent = `${text('preview')} ${JSON.stringify(entry.args.map(expand))}\n${text('cwd')} ${directory === defaultDirectory && !context?.projectFolder ? '—' : expand(directory)}`;
172
+ };
173
+ preview.style.whiteSpace = 'pre-wrap';
174
+ preview.style.overflowWrap = 'anywhere';
175
+ previews.set(entry.id, updatePreview);
176
+ updatePreview();
177
+ args.oninput = () => {
178
+ entry.args = args.value ? args.value.split('\n') : [];
179
+ updatePreview();
180
+ };
181
+ cwd.oninput = () => {
182
+ entry.cwd = cwd.value;
183
+ updatePreview();
184
+ };
185
+ const move = (offset) => {
186
+ entries.splice(index, 1);
187
+ entries.splice(index + offset, 0, entry);
188
+ render();
189
+ list.children[index + offset].querySelector('input')?.focus();
190
+ };
191
+ const up = button('up', () => move(-1));
192
+ const down = button('down', () => move(1));
193
+ up.disabled = index === 0;
194
+ down.disabled = index === entries.length - 1;
195
+ const remove = button('remove', () => {
196
+ entries.splice(index, 1);
197
+ render();
198
+ (list.children[Math.min(index, entries.length - 1)]?.querySelector('input') ?? add).focus();
199
+ });
200
+ const tryLaunch = button('test', () => {
201
+ const original = saved.entries.find(item => item.id === entry.id);
202
+ if (!original || JSON.stringify(toDraft(original)) !== JSON.stringify(toDraft(entry))) {
203
+ status.textContent = text('saveFirst');
204
+ return;
205
+ }
206
+ void run(() => port.launch(entry.id), () => { status.textContent = text('launched'); });
207
+ });
208
+ row.append(field('name', name), application, choose, field('args', args), field('cwd', cwd), preview, field('url', url), up, down, remove, tryLaunch);
209
+ list.append(row);
210
+ }
211
+ }
212
+ section.addEventListener('keydown', event => {
213
+ if (event.key === 'Enter' && event.target.tagName === 'INPUT')
214
+ event.preventDefault();
215
+ });
216
+ section.append(make('legend', undefined, text('section')), make('p', styles.aiAgentDialogNote, text('variables')), button('chooseProject', () => chooseContext('project')), button('chooseRepository', () => chooseContext('repository')), contextSummary, list, add, save, status);
217
+ section.disabled = true;
218
+ // The dialog attaches this section to the document before the requests resolve.
219
+ void Promise.all([agentRequest(() => port.list()), agentRequest(() => port.context())]).then(([settings, current]) => {
220
+ if (!section.isConnected)
221
+ return;
222
+ if ('code' in settings) {
223
+ status.textContent = desktopAgentError(settings.code, locale);
224
+ return;
225
+ }
226
+ saved = settings.value;
227
+ entries = saved.entries.map(entry => ({ ...entry }));
228
+ if ('value' in current)
229
+ context = current.value;
230
+ refreshPreviews();
231
+ section.disabled = false;
232
+ render();
233
+ });
234
+ return section;
235
+ }