dsh-subscription-agents 0.0.0-stage → 1.2.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/client.js ADDED
@@ -0,0 +1,588 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-subscription-agents',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const { useEffect, useRef, useState, useId } = React;
7
+ const NS = 'subscriptionAgents';
8
+ const PANEL = 'subscription-agents';
9
+ const providers = { codex: 'Codex', claude: 'Claude Code' };
10
+ const signInHosts = {
11
+ codex: new Set(['auth.openai.com', 'login.openai.com']),
12
+ claude: new Set(['claude.ai', 'console.anthropic.com', 'platform.claude.com']),
13
+ };
14
+ const ru = {
15
+ panel: 'Агенты по подписке', title: 'Агенты по подписке',
16
+ intro: 'Подключите Codex и Claude Code как полноценных агентов проекта с отдельными дочерними чатами.',
17
+ privacy: 'CLI-агенты работают в папке проекта: могут читать и изменять файлы и выполнять команды в пределах настроенных разрешений. Переписка и действия видны в дочернем чате.',
18
+ add: 'Добавить аккаунт', addTitle: 'Новый аккаунт', addHelp: 'Новый аккаунт выключен. Сначала войдите в него, затем разрешите делегирование.',
19
+ refreshAll: 'Обновить лимиты', refresh: 'Обновить', verifySignIn: 'Проверить вход', retry: 'Повторить загрузку',
20
+ provider: 'Провайдер', name: 'Название (необязательно)', editName: 'Название', nameHint: 'Например: Личный аккаунт',
21
+ noCli: 'CLI не найден', noProviders: 'Установите Codex CLI или Claude Code на компьютере, где запущен DSH.',
22
+ accounts: 'Аккаунты', loading: 'Загрузка аккаунтов…', empty: 'Аккаунтов пока нет', emptyHelp: 'Добавьте аккаунт и войдите в него в браузере на компьютере с DSH.',
23
+ listError: 'Не удалось загрузить аккаунты.', staleList: 'Не удалось обновить список. Показаны последние полученные данные.',
24
+ requestError: 'Не удалось связаться с DSH.', invalidResponse: 'Сервер вернул неожиданный ответ.', sessionError: 'Откройте или обновите авторизованную страницу DSH.',
25
+ unknown: 'Статус неизвестен', new: 'Нужен вход', loginStatus: 'Ожидает входа', ready: 'Готов', error: 'Требует внимания',
26
+ login: 'Войти', loginAgain: 'Войти заново', stop: 'Отменить вход', loginHelp: 'Завершите вход в системном браузере на компьютере с DSH. Статус обновится здесь.', openSignIn: 'Открыть страницу входа', delegating: 'Агент выполняет поручение…',
27
+ test: 'Проверить', rename: 'Переименовать', remove: 'Удалить', save: 'Сохранить', close: 'Отмена',
28
+ enabled: 'Делегирование разрешено', disabled: 'Делегирование выключено', switchLabel: 'Разрешить делегирование', gate: 'Перед включением пройдите проверку аккаунта: нажмите «Проверить».',
29
+ confirmEnable: 'Разрешить делегирование этому аккаунту?', enableHelp: 'Агент получает доступ к проекту и может отправлять содержимое прочитанных файлов своему провайдеру. Сейчас запуск доступен только из сессии DSH с полным доступом. Codex ограничивает запись рабочей областью; Claude Code использует acceptEdits. Включайте только для доверенных проектов.', enable: 'Разрешить',
30
+ confirmRemove: 'Удалить аккаунт из плагина?', removeHelp: 'Плагин удалит аккаунт из списка и завершит его сеанс CLI, если он был подключён.',
31
+ footer: 'Лимиты агентов', left: 'осталось {percent}%', usageCaveat: 'Claude Code сообщает о лимитах не при каждой проверке. Здесь показаны последние доступные данные.',
32
+ usage: 'Лимиты подписки', usageUnknown: 'Нет данных о лимитах', usageStale: 'Данные могли устареть', lastUpdated: 'Обновлено: {date}', lastChecked: 'Проверено: {date}',
33
+ period: 'Лимит', fiveHour: 'Пятичасовой лимит', weekly: 'Недельный лимит', untilReset: 'До сброса: {duration}', resetPending: 'Ожидается обновление лимита', dayUnit: 'дн.', hourUnit: 'ч', minuteUnit: 'мин', underMinute: 'меньше минуты', durationReset: 'Сброс: {date}', resetUnknown: 'Сброс неизвестен',
34
+ adding: 'Добавление…', launching: 'Запуск входа…', cancelling: 'Отмена входа…', refreshing: 'Обновление лимитов…', testing: 'Проверка аккаунта…',
35
+ saving: 'Сохранение…', removing: 'Удаление…', working: 'Операция выполняется…',
36
+ added: 'Аккаунт добавлен. Теперь можно войти.', launched: 'Запрошен вход. Проверьте системный браузер на компьютере с DSH.',
37
+ cancelled: 'Вход отменён.', refreshed: 'Запрошено обновление лимитов.', tested: 'Проверка запущена. Результат появится в карточке аккаунта.',
38
+ taskAgents: 'Агенты этой задачи', parentChat: 'Основной чат', childChat: 'Дочерний чат', nativeChat: 'Открыть обычный чат агента', runningChild: 'Работает', idleChild: 'Неактивен', completedChild: 'Завершён', waitingChild: 'Ожидает решения', childLoadError: 'Не удалось обновить список агентов.', refreshChildren: 'Обновить список агентов',
39
+ saved: 'Название сохранено.', switched: 'Настройка делегирования сохранена.', removed: 'Аккаунт удалён.',
40
+ };
41
+ const en = {
42
+ panel: 'Subscription agents', title: 'Subscription agents',
43
+ intro: 'Connect Codex and Claude Code as full project agents with their own child conversations.',
44
+ privacy: 'CLI agents work in the project directory: they can read and edit files and run commands within configured permissions. Their conversation and activity appear in the child chat.',
45
+ add: 'Add account', addTitle: 'New account', addHelp: 'The new account starts disabled. Sign in first, then allow delegation.',
46
+ refreshAll: 'Refresh limits', refresh: 'Refresh', verifySignIn: 'Check sign-in', retry: 'Retry loading',
47
+ provider: 'Provider', name: 'Name (optional)', editName: 'Name', nameHint: 'For example: Personal account',
48
+ noCli: 'CLI not found', noProviders: 'Install Codex CLI or Claude Code on the computer running DSH.',
49
+ accounts: 'Accounts', loading: 'Loading accounts…', empty: 'No accounts yet', emptyHelp: 'Add an account and sign in using the browser on the computer running DSH.',
50
+ listError: 'Could not load accounts.', staleList: 'Could not reload the list. Showing the last snapshot.',
51
+ requestError: 'Could not contact DSH.', invalidResponse: 'The server returned an unexpected response.', sessionError: 'Open or reload an authenticated DSH page.',
52
+ unknown: 'Status unknown', new: 'Sign-in required', loginStatus: 'Waiting for sign-in', ready: 'Ready', error: 'Needs attention',
53
+ login: 'Sign in', loginAgain: 'Sign in again', stop: 'Cancel sign-in', loginHelp: 'Complete sign-in in the system browser on the computer running DSH. The status will update here.', openSignIn: 'Open sign-in page', delegating: 'Agent is working on a delegated prompt…',
54
+ test: 'Test', rename: 'Rename', remove: 'Remove', save: 'Save', close: 'Cancel',
55
+ enabled: 'Delegation allowed', disabled: 'Delegation off', switchLabel: 'Allow delegation', gate: 'Before enabling delegation, select Test and wait for the account to pass.',
56
+ confirmEnable: 'Allow delegation to this account?', enableHelp: 'The agent receives project access and may send the contents of files it reads to its provider. Launch currently requires a DSH session with Full access. Codex limits writes to the workspace; Claude Code uses acceptEdits. Enable only for trusted projects.', enable: 'Allow',
57
+ confirmRemove: 'Remove this account from the plugin?', removeHelp: 'The plugin will remove the account from the list and sign out its CLI session if it was connected.',
58
+ footer: 'Agent limits', left: '{percent}% remaining', usageCaveat: 'Claude Code does not report limits on every check. The last available data is shown here.',
59
+ usage: 'Subscription limits', usageUnknown: 'No usage data', usageStale: 'Usage data may be out of date', lastUpdated: 'Updated: {date}', lastChecked: 'Checked: {date}',
60
+ period: 'Limit', fiveHour: 'Five-hour limit', weekly: 'Weekly limit', untilReset: 'Resets in: {duration}', resetPending: 'Waiting for updated limits', dayUnit: 'd', hourUnit: 'h', minuteUnit: 'min', underMinute: 'less than a minute', durationReset: 'Resets: {date}', resetUnknown: 'Reset time unknown',
61
+ adding: 'Adding…', launching: 'Opening sign-in…', cancelling: 'Cancelling sign-in…', refreshing: 'Refreshing limits…', testing: 'Testing account…',
62
+ saving: 'Saving…', removing: 'Removing…', working: 'Working…',
63
+ added: 'Account added. You can now sign in.', launched: 'Sign-in requested. Check the system browser on the computer running DSH.',
64
+ cancelled: 'Sign-in cancelled.', refreshed: 'Limit refresh requested.', tested: 'Test started. The result will appear on the account card.',
65
+ taskAgents: 'Task agents', parentChat: 'Parent conversation', childChat: 'Child conversation', nativeChat: 'Open the agent conversation', runningChild: 'Running', idleChild: 'Inactive', completedChild: 'Completed', waitingChild: 'Waiting for input', childLoadError: 'Could not refresh the agent list.', refreshChildren: 'Refresh agent list',
66
+ saved: 'Name saved.', switched: 'Delegation setting saved.', removed: 'Account removed.',
67
+ };
68
+ const styles = `
69
+ .dsa-panel { box-sizing:border-box; block-size:100%; min-block-size:0; overflow:auto; color:var(--dsw-alias-label-primary); font-size:14px; line-height:1.5; }
70
+ .dsa-panel *, .dsa-panel *::before, .dsa-panel *::after { box-sizing:border-box; }
71
+ .dsa-inner { max-inline-size:960px; margin-inline:auto; padding:clamp(20px,4vw,44px); padding-block-end:48px; display:grid; gap:24px; min-inline-size:0; }
72
+ .dsa-head, .dsa-list, .dsa-card, .dsa-form { display:grid; gap:12px; min-inline-size:0; }
73
+ .dsa-panel h1, .dsa-panel h2, .dsa-panel h3, .dsa-panel p { margin:0; overflow-wrap:anywhere; }
74
+ .dsa-panel h1 { font-size:26px; line-height:1.25; letter-spacing:-.025em; font-weight:650; }
75
+ .dsa-panel h2 { font-size:13px; color:var(--dsw-alias-label-secondary); font-weight:600; }
76
+ .dsa-panel h3 { font-size:17px; font-weight:630; letter-spacing:-.015em; }
77
+ .dsa-head > p { max-inline-size:72ch; }
78
+ .dsa-subtle, .dsa-meta { color:var(--dsw-alias-label-secondary); }
79
+ .dsa-meta { font-size:12px; }
80
+ .dsa-toolbar, .dsa-row { display:flex; flex-wrap:wrap; align-items:center; gap:8px; min-inline-size:0; }
81
+ .dsa-toolbar { margin-block-start:6px; }
82
+ .dsa-spread { justify-content:space-between; }
83
+ .dsa-card, .dsa-form, .dsa-message { padding:clamp(16px,2.4vw,24px); border:1px solid var(--dsw-alias-border-l1); border-radius:16px; background:var(--dsw-alias-bg-layer-1); }
84
+ .dsa-card { gap:18px; }
85
+ .dsa-card > header > div { display:grid; gap:3px; }
86
+ .dsa-form { gap:14px; background:var(--dsw-alias-bg-layer-2); }
87
+ .dsa-panel fieldset { margin:0; min-inline-size:0; }
88
+ .dsa-panel legend { padding-inline:5px; font-weight:600; }
89
+ .dsa-fields { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,195px),1fr)); gap:12px; }
90
+ .dsa-field { display:grid; gap:6px; min-inline-size:0; }
91
+ .dsa-panel button, .dsa-panel input, .dsa-panel select { font:inherit; font-size:13px; min-inline-size:0; max-inline-size:100%; border:1px solid var(--dsw-alias-border-l2); border-radius:9px; color:var(--dsw-alias-label-primary); background:var(--dsw-alias-bg-layer-1); min-block-size:34px; box-shadow:none; }
92
+ .dsa-panel button { padding:6px 12px; cursor:pointer; white-space:normal; overflow-wrap:anywhere; text-align:start; }
93
+ .dsa-panel input, .dsa-panel select { inline-size:100%; padding:7px 10px; }
94
+ .dsa-panel button.dsa-primary { border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 40%,var(--dsw-alias-border-l1)); background:color-mix(in srgb,var(--dsw-alias-brand-primary) 14%,var(--dsw-alias-bg-layer-1)); color:var(--dsw-alias-label-primary); font-weight:600; }
95
+ .dsa-panel button.dsa-danger { color:var(--dsw-alias-state-error-primary); }
96
+ .dsa-panel button:disabled { opacity:.45; cursor:not-allowed; }
97
+ .dsa-panel :is(button,input,select,a):focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:3px; }
98
+ .dsa-panel button:not(:disabled):active { transform:scale(.98); }
99
+ @media (hover:hover) and (pointer:fine) {
100
+ .dsa-panel button:not(:disabled):hover { background:var(--dsw-alias-bg-layer-2); }
101
+ .dsa-panel button.dsa-primary:not(:disabled):hover { background:color-mix(in srgb,var(--dsw-alias-brand-primary) 22%,var(--dsw-alias-bg-layer-1)); }
102
+ }
103
+ @media (pointer:coarse) { .dsa-panel input, .dsa-panel select { font-size:16px; } .dsa-panel button { min-block-size:42px; } }
104
+ .dsa-badge { display:inline-flex; align-items:center; gap:6px; max-inline-size:100%; overflow-wrap:anywhere; border-radius:999px; padding:3px 9px; font-size:11px; font-weight:550; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-secondary); }
105
+ .dsa-badge::before { content:''; inline-size:5px; block-size:5px; border-radius:50%; background:currentColor; flex:none; }
106
+ .dsa-badge[data-status=ready] { color:var(--dsw-alias-state-success-primary); }
107
+ .dsa-badge[data-status=error], .dsa-error { color:var(--dsw-alias-state-error-primary); }
108
+ .dsa-badge[data-status=login], .dsa-warn { color:var(--dsw-alias-state-warn-primary); }
109
+ .dsa-usage { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr)); gap:14px; min-inline-size:0; }
110
+ .dsa-usage > :not(.dsa-window) { grid-column:1/-1; }
111
+ .dsa-usage > .dsa-row strong { font-size:12px; font-weight:550; color:var(--dsw-alias-label-secondary); }
112
+ .dsa-window { display:grid; gap:10px; min-inline-size:0; padding:16px; border:1px solid var(--dsw-alias-border-l1); border-radius:12px; background:var(--dsw-alias-bg-base); }
113
+ .dsa-window > strong { font-size:13px; font-weight:550; }
114
+ .dsa-window .dsa-row { align-items:baseline; gap:6px; }
115
+ .dsa-window .dsa-row > :last-child { color:var(--dsw-alias-label-primary); font-variant-numeric:tabular-nums; font-weight:600; }
116
+ .dsa-track { display:block; block-size:5px; border-radius:999px; overflow:hidden; background:var(--dsw-alias-border-l1); }
117
+ .dsa-track span { display:block; block-size:100%; border-radius:inherit; background:var(--dsw-alias-brand-primary); }
118
+ .dsa-track[data-stale=true] span { background:var(--dsw-alias-label-secondary); }
119
+ .dsa-panel a { color:var(--dsw-alias-brand-primary); text-decoration:underline; text-underline-offset:3px; }
120
+ .dsa-note { white-space:pre-wrap; overflow-wrap:anywhere; }
121
+ .dsa-actions { padding-block-start:14px; border-block-start:1px solid var(--dsw-alias-border-l1); gap:4px; }
122
+ .dsa-actions button { border-color:transparent; background:transparent; padding-inline:9px; color:var(--dsw-alias-label-secondary); font-size:12px; }
123
+ .dsa-actions button.dsa-primary { color:var(--dsw-alias-label-primary); }
124
+ .dsa-actions button.dsa-danger { margin-inline-start:auto; }
125
+ .dsa-panel button.dsa-switch { display:inline-flex; gap:9px; align-items:center; padding:0; min-block-size:28px; background:transparent; border:0; color:var(--dsw-alias-label-secondary); font-size:12px; }
126
+ .dsa-panel button.dsa-switch:hover { background:transparent; }
127
+ .dsa-switch-mark { inline-size:28px; block-size:16px; padding:2px; border-radius:999px; display:inline-flex; flex:none; background:var(--dsw-alias-border-l2); }
128
+ .dsa-switch-mark::before { content:''; inline-size:12px; block-size:12px; border-radius:50%; background:var(--dsw-alias-label-primary); }
129
+ .dsa-switch[aria-checked=true] .dsa-switch-mark { justify-content:flex-end; background:var(--dsw-alias-brand-primary); }
130
+ @media (pointer:coarse) { .dsa-panel button.dsa-switch { min-block-size:42px; } }
131
+ @media (max-width:600px) { .dsa-usage { grid-template-columns:minmax(0,1fr); } .dsa-inner { padding:20px 16px; } .dsa-usage > .dsa-row { align-items:start; } }
132
+ `;
133
+ const footerStyles = `
134
+ .dsa-footer { display:grid; gap:2px; min-inline-size:0; }
135
+ .dsa-footer button { display:flex; align-items:center; gap:6px; inline-size:100%; min-inline-size:0; min-block-size:32px; border:0; border-radius:8px; background:transparent; color:var(--dsw-alias-label-primary); padding:4px 8px; font:inherit; text-align:start; cursor:pointer; }
136
+ .dsa-footer button:focus-visible { outline:2px solid var(--dsw-alias-state-business-primary); outline-offset:-2px; }
137
+ @media (hover:hover) { .dsa-footer button:hover { background:var(--dsw-alias-button-tool-bar-hover); } }
138
+ .dsa-footer[data-rail] button { inline-size:36px; min-block-size:36px; justify-content:center; padding:0; margin-inline:auto; }
139
+ .dsa-footer h2 { margin:0; font-size:.88em; font-weight:600; }
140
+ .dsa-footer svg { flex:none; }
141
+ .dsa-footer-label { flex:1; min-inline-size:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
142
+ .dsa-footer-value { flex:none; color:var(--dsw-alias-label-secondary); font-size:.88em; font-variant-numeric:tabular-nums; }
143
+ .dsa-footer-rows { max-block-size:min(106px,16vh); overflow:auto; padding-inline-start:8px; }
144
+ `;
145
+ const progress = { add: 'adding', login: 'launching', cancel: 'cancelling', refresh: 'refreshing', test: 'testing', rename: 'saving', toggle: 'saving', remove: 'removing', delegate: 'delegating' };
146
+ const success = { add: 'added', login: 'launched', cancel: 'cancelled', refresh: 'refreshed', test: 'tested', rename: 'saved', toggle: 'switched', remove: 'removed' };
147
+
148
+ async function call(action, payload, signal) {
149
+ const base = document.querySelector('base[href]') ? document.baseURI : new URL('.', window.location.href);
150
+ const url = new URL('api/subscription-agents', base);
151
+ if (url.origin !== window.location.origin) return { ok: false, message: 'requestError' };
152
+ try {
153
+ const deadline = AbortSignal.timeout(action === 'remove' ? 90000 : 20000);
154
+ const response = await fetch(url, {
155
+ method: 'POST', credentials: 'same-origin', redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
156
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-DSH-Subscription-Agents': '1' },
157
+ body: JSON.stringify({ ...payload, action }),
158
+ });
159
+ if ([401, 403].includes(response.status)) return { ok: false, message: 'sessionError' };
160
+ const result = await response.json().catch(() => null);
161
+ if (signal?.aborted) return null;
162
+ if (response.ok && result?.ok === true) return result;
163
+ return { ok: false, message: 'invalidResponse', error: typeof result?.error === 'string' ? result.error : undefined };
164
+ } catch {
165
+ return signal?.aborted ? null : { ok: false, message: 'requestError' };
166
+ }
167
+ }
168
+
169
+ function safeLoginUrl(account) {
170
+ if (typeof account.loginUrl !== 'string') return null;
171
+ try {
172
+ const url = new URL(account.loginUrl);
173
+ return url.protocol === 'https:' && !url.username && !url.password && !url.port
174
+ && /oauth|authorize/.test(url.pathname) && url.href.length < 8192
175
+ && signInHosts[account.provider]?.has(url.hostname) ? url.href : null;
176
+ } catch { return null; }
177
+ }
178
+ function stamp(value) {
179
+ return Number.isFinite(value) && value > 0 && !Number.isNaN(new Date(value).getTime()) ? value : null;
180
+ }
181
+ function formatDate(value) {
182
+ const date = new Date(value);
183
+ try { return new Intl.DateTimeFormat(document.documentElement.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date); }
184
+ catch { return date.toLocaleString(); }
185
+ }
186
+ function Button({ children, type = 'button', variant, ...props }) {
187
+ return h('button', { type, ...props, className: [props.className, variant && `dsa-${variant}`].filter(Boolean).join(' ') }, children);
188
+ }
189
+ function PanelIcon() {
190
+ return h('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
191
+ h('rect', { x: 2.25, y: 3, width: 11.5, height: 10, rx: 2 }),
192
+ h('path', { d: 'm4.75 6 2 2-2 2m3.75 0h2.75' }));
193
+ }
194
+
195
+ function isStale(account, win, now) {
196
+ const sample = stamp(win.sampledAt) ?? stamp(account.usage?.updatedAt);
197
+ const reset = stamp(win.resetAt);
198
+ return !sample || now - sample >= 6 * 60 * 1000 || account.status === 'error' || (reset !== null && reset <= now);
199
+ }
200
+ function remaining(account) {
201
+ const windows = account.usage?.windows;
202
+ if (account.status !== 'ready' || !Array.isArray(windows)) return null;
203
+ const window = windows.find(win => win && /^(5\s*h|5 часов)$/.test(typeof win.label === 'string' ? win.label.trim() : ''));
204
+ if (!window || !Number.isFinite(window.usedPercent) || isStale(account, window, Date.now())) return null;
205
+ return percentLeft(window.usedPercent);
206
+ }
207
+
208
+ function SidebarUsage({ wide, t, openPanel }) {
209
+ const [snapshot, setSnapshot] = useState(null);
210
+ useEffect(() => {
211
+ if (!wide) return undefined;
212
+ const controller = new AbortController();
213
+ let active = false;
214
+ async function update() {
215
+ if (active || document.visibilityState === 'hidden') return;
216
+ active = true;
217
+ const result = await call('list', {}, controller.signal);
218
+ active = false;
219
+ if (controller.signal.aborted) return;
220
+ setSnapshot(result?.ok && Array.isArray(result.accounts) ? result.accounts : null);
221
+ }
222
+ void update();
223
+ const timer = window.setInterval(update, 20000);
224
+ document.addEventListener('visibilitychange', update);
225
+ return () => { controller.abort(); window.clearInterval(timer); document.removeEventListener('visibilitychange', update); };
226
+ }, [wide]);
227
+ return h('section', { className: 'dsa-footer', 'data-rail': !wide || undefined, 'aria-label': t('footer') }, h('style', null, footerStyles),
228
+ h('h2', null, h('button', { type: 'button', onClick: () => openPanel(), 'aria-label': t('footer'), title: t('footer') }, h(PanelIcon),
229
+ wide && h('span', { className: 'dsa-footer-label' }, t('footer')))),
230
+ wide && snapshot?.length > 0 && h('div', { className: 'dsa-footer-rows' }, snapshot.map(account => {
231
+ const name = `#${account.number} · ${account.name || providers[account.provider] || t('unknown')}`;
232
+ const value = remaining(account);
233
+ const title = `${name} · ${t('fiveHour')}: ${value === null ? t('usageUnknown') : t('left', { percent: value })}`;
234
+ return h('button', { key: account.id, type: 'button', title, 'aria-label': title, onClick: () => openPanel(account.id) },
235
+ h('span', { className: 'dsa-footer-label' }, name), h('span', { className: 'dsa-footer-value', 'aria-hidden': true }, value === null ? '—' : `${value}%`));
236
+ })));
237
+ }
238
+
239
+ function TaskAgents({ wide, t, useSessions, useSessionStatus, openNativeSession, refreshChildren }) {
240
+ const listing = useSessions(state => state);
241
+ const statuses = useSessionStatus(state => state);
242
+ const current = Object.values(listing.byId).find(row => (row.retainedBy?.mainView ?? 0) > 0);
243
+ const parentId = current?.origin === 'subagent' ? current.parentId : current?.id;
244
+ const summary = parentId ? listing.byId[parentId] : undefined;
245
+ const catalog = parentId ? listing.projectionsBySession[parentId] : undefined;
246
+ const children = (catalog?.values?.subagentCatalog ?? []).filter(entry => entry.mode === 'continuable');
247
+ const [error, setError] = useState(false);
248
+ const [refreshing, setRefreshing] = useState(false);
249
+ useEffect(() => {
250
+ let disposed = false;
251
+ setError(false);
252
+ if (!parentId) return undefined;
253
+ setRefreshing(true);
254
+ Promise.resolve(refreshChildren(parentId)).catch(() => { if (!disposed) setError(true); })
255
+ .finally(() => { if (!disposed) setRefreshing(false); });
256
+ return () => { disposed = true; };
257
+ }, [parentId]);
258
+ async function retry() {
259
+ if (refreshing || !parentId) return;
260
+ setRefreshing(true); setError(false);
261
+ try { await refreshChildren(parentId); } catch { setError(true); }
262
+ finally { setRefreshing(false); }
263
+ }
264
+ if (!parentId || (children.length === 0 && !error)) return null;
265
+ const parentTitle = summary?.displayTitle || t('parentChat');
266
+ return h('section', { className: 'dsa-footer dsa-task-tree', 'data-rail': !wide || undefined, 'aria-label': t('taskAgents') },
267
+ h('style', null, footerStyles + `
268
+ .dsa-task-tree { border-block-start:1px solid var(--dsw-alias-border-l1); padding-block-start:7px; margin-block-end:7px; }
269
+ .dsa-task-tree .dsa-child-list { margin:0 0 0 14px; padding:0 0 0 5px; list-style:none; border-inline-start:1px solid var(--dsw-alias-border-l1); max-block-size:min(180px,24vh); overflow:auto; }
270
+ .dsa-task-tree .dsa-child-label { display:grid; gap:1px; flex:1; min-inline-size:0; }
271
+ .dsa-task-tree .dsa-child-status { font-size:10px; color:var(--dsw-alias-label-secondary); }
272
+ .dsa-task-tree .dsa-child-dot { inline-size:5px; block-size:5px; border-radius:50%; background:var(--dsw-alias-label-secondary); flex:none; }
273
+ .dsa-task-tree .dsa-child-dot[data-status=running] { background:var(--dsw-alias-brand-primary); }
274
+ .dsa-task-tree .dsa-child-dot[data-status=waiting] { background:var(--dsw-alias-state-warn-primary); }
275
+ .dsa-task-tree button[aria-current=page] { background:var(--dsw-alias-bg-layer-2); }
276
+ .dsa-task-tree .dsa-tree-tools { display:flex; align-items:center; gap:3px; }
277
+ .dsa-task-tree .dsa-tree-refresh { inline-size:28px; flex:none; justify-content:center; padding:3px; }
278
+ .dsa-task-tree .dsa-tree-error { margin:4px 8px; color:var(--dsw-alias-state-error-primary); font-size:11px; }
279
+ `),
280
+ h('h2', { className: 'dsa-tree-tools' },
281
+ h('button', { type: 'button', onClick: () => openNativeSession(parentId), title: t('taskAgents'), 'aria-label': t('taskAgents') },
282
+ h(PanelIcon), wide && h('span', { className: 'dsa-footer-label' }, t('taskAgents'))),
283
+ wide && h('button', { type: 'button', className: 'dsa-tree-refresh', disabled: refreshing, 'aria-label': t('refreshChildren'), title: t('refreshChildren'), onClick: retry }, '↻')),
284
+ wide && h('button', { type: 'button', title: `${t('parentChat')}: ${parentTitle}`, 'aria-label': `${t('parentChat')}: ${parentTitle}`, 'aria-current': current?.id === parentId ? 'page' : undefined, onClick: () => openNativeSession(parentId) },
285
+ h('span', { 'aria-hidden': true }, '↖'), h('span', { className: 'dsa-footer-label' }, parentTitle)),
286
+ wide && children.length > 0 && h('ul', { className: 'dsa-child-list' }, children.map(entry => {
287
+ const childSummary = listing.byId[entry.id];
288
+ const status = statuses.get(entry.id);
289
+ const activity = status?.pendingInteraction ? 'waiting' : (status?.running ?? childSummary?.running) ? 'running'
290
+ : childSummary?.projectionValues?.subagentTiming?.lastTurnCompleted === true ? 'completed' : 'idle';
291
+ const title = entry.label || entry.name || childSummary?.displayTitle || t('childChat');
292
+ const statusText = t({ waiting:'waitingChild', running:'runningChild', completed:'completedChild', idle:'idleChild' }[activity]);
293
+ return h('li', { key: entry.id }, h('button', {
294
+ type: 'button', title: `${title} · ${statusText}`, 'aria-label': `${t('nativeChat')}: ${title} · ${statusText}`,
295
+ 'aria-current': current?.id === entry.id ? 'page' : undefined,
296
+ onClick: () => openNativeSession({ parentSessionId: parentId, childSessionId: entry.id, mode: entry.mode }),
297
+ }, h('span', { className: 'dsa-child-dot', 'data-status': activity, 'aria-hidden': true }),
298
+ h('span', { className: 'dsa-child-label' }, h('span', { className: 'dsa-footer-label' }, title), h('span', { className: 'dsa-child-status' }, statusText))));
299
+ })),
300
+ wide && error && h('p', { role: 'status', className: 'dsa-tree-error' }, t('childLoadError')));
301
+ }
302
+
303
+ function percentLeft(used) {
304
+ return Number.isFinite(used) ? Math.max(0, Math.min(100, Math.floor(100 - used))) : null;
305
+ }
306
+ function resetDuration(reset, now, t) {
307
+ const minutes = Math.floor((reset - now) / 60000);
308
+ if (reset <= now) return t('resetPending');
309
+ if (minutes < 1) return t('untilReset', { duration: t('underMinute') });
310
+ const days = Math.floor(minutes / 1440);
311
+ const hours = Math.floor(minutes % 1440 / 60);
312
+ const mins = minutes % 60;
313
+ const duration = days ? `${days} ${t('dayUnit')}${hours ? ` ${hours} ${t('hourUnit')}` : ''}`
314
+ : hours ? `${hours} ${t('hourUnit')}${mins ? ` ${mins} ${t('minuteUnit')}` : ''}` : `${mins} ${t('minuteUnit')}`;
315
+ return t('untilReset', { duration });
316
+ }
317
+ function Usage({ account, t }) {
318
+ const [now, setNow] = useState(Date.now);
319
+ useEffect(() => {
320
+ const update = () => setNow(Date.now());
321
+ const timer = window.setInterval(update, 1000);
322
+ document.addEventListener('visibilitychange', update);
323
+ return () => { window.clearInterval(timer); document.removeEventListener('visibilitychange', update); };
324
+ }, []);
325
+ const windows = Array.isArray(account.usage?.windows) ? account.usage.windows.filter(win => win && typeof win === 'object') : [];
326
+ const updated = stamp(account.usage?.updatedAt);
327
+ const checked = stamp(account.checkedAt);
328
+ const stale = windows.some(win => isStale(account, win, now));
329
+ return h('section', { className: 'dsa-usage', 'aria-label': t('usage') },
330
+ h('div', { className: 'dsa-row dsa-spread' }, h('strong', null, t('usage')),
331
+ windows.length > 0 && updated && h('span', { className: 'dsa-meta' }, t('lastUpdated', { date: formatDate(updated) }))),
332
+ stale && h('p', { className: 'dsa-meta dsa-warn' }, t('usageStale')),
333
+ windows.length === 0 && h('p', { className: 'dsa-meta' }, t('usageUnknown')),
334
+ windows.map((win, index) => {
335
+ const pct = percentLeft(win.usedPercent);
336
+ const rawLabel = typeof win.label === 'string' ? win.label.trim() : '';
337
+ const label = /^(5\s*h|5 часов)$/.test(rawLabel) ? t('fiveHour') : /^(7\s*d|7 дней)$/.test(rawLabel) ? t('weekly') : rawLabel || t('period');
338
+ const reset = stamp(win.resetAt);
339
+ return h('div', { className: 'dsa-window', key: index },
340
+ h('strong', null, label),
341
+ h('div', { className: 'dsa-row dsa-spread' },
342
+ h('span', { className: 'dsa-meta', title: reset ? t('durationReset', { date: formatDate(reset) }) : undefined }, reset ? resetDuration(reset, now, t) : t('resetUnknown')),
343
+ h('span', { className: 'dsa-meta' }, pct === null ? t('usageUnknown') : t('left', { percent: pct }))),
344
+ pct !== null && h('div', { className: 'dsa-track', 'aria-hidden': true, 'data-stale': isStale(account, win, now) }, h('span', { style: { width: `${pct}%` } })));
345
+ }),
346
+ account.provider === 'claude' && h('p', { className: 'dsa-meta' }, t('usageCaveat')),
347
+ checked !== null && checked !== updated && h('p', { className: 'dsa-meta' }, t('lastChecked', { date: formatDate(checked) })));
348
+ }
349
+
350
+ function Editor({ kind, account, available, onSubmit, onClose, pending, t }) {
351
+ const add = kind === 'add';
352
+ const rename = kind === 'rename';
353
+ const remove = kind === 'remove';
354
+ const enable = kind === 'enable';
355
+ const choices = Object.keys(providers).filter(provider => available[provider] === true);
356
+ const [provider, setProvider] = useState(choices[0] || '');
357
+ const [name, setName] = useState(rename ? account.name || '' : '');
358
+ const first = useRef(null);
359
+ useEffect(() => { first.current?.focus(); }, []);
360
+ const effectiveProvider = choices.includes(provider) ? provider : choices[0] || '';
361
+ return h('form', {
362
+ onSubmit(event) {
363
+ event.preventDefault();
364
+ if (pending || (add && !effectiveProvider) || (rename && !name.trim())) return;
365
+ if (add) onSubmit('add', { provider: effectiveProvider, ...(name.trim() ? { name: name.trim() } : {}) });
366
+ else if (rename) onSubmit('rename', { id: account.id, name: name.trim() });
367
+ else if (remove) onSubmit('remove', { id: account.id });
368
+ else onSubmit('toggle', { id: account.id, enabled: true });
369
+ },
370
+ onKeyDown(event) {
371
+ if (event.key === 'Escape' && !pending) { event.stopPropagation(); onClose(); }
372
+ },
373
+ }, h('fieldset', { className: 'dsa-form', disabled: pending },
374
+ h('legend', null, t(add ? 'addTitle' : rename ? 'rename' : remove ? 'confirmRemove' : 'confirmEnable')),
375
+ (add || remove || enable) && h('p', { className: 'dsa-subtle' }, t(add ? 'addHelp' : remove ? 'removeHelp' : 'enableHelp')),
376
+ (add || rename) && h('div', { className: 'dsa-fields' },
377
+ add && h('label', { className: 'dsa-field' }, t('provider'), h('select', {
378
+ ref: first, value: effectiveProvider, onChange: event => setProvider(event.target.value), required: true,
379
+ }, !effectiveProvider && h('option', { value: '' }, t('noCli')),
380
+ Object.entries(providers).map(([id, label]) => h('option', { value: id, key: id, disabled: !available[id] }, available[id] ? label : `${label} — ${t('noCli')}`)))),
381
+ h('label', { className: 'dsa-field' }, t(add ? 'name' : 'editName'), h('input', {
382
+ ref: rename ? first : undefined, value: name, onChange: event => setName(event.target.value), placeholder: t('nameHint'), maxLength: 70, required: rename,
383
+ }))),
384
+ h('div', { className: 'dsa-row' },
385
+ h('button', { type: 'button', ref: remove || enable ? first : undefined, onClick: onClose }, t('close')),
386
+ h(Button, { type: 'submit', variant: remove ? 'danger' : 'primary', disabled: (add && !effectiveProvider) || (rename && !name.trim()) },
387
+ t(add ? 'add' : rename ? 'save' : remove ? 'remove' : 'enable')))));
388
+ }
389
+
390
+ function Account({ account, available, edit, pending, begin, close, run, notice, focusTarget, t }) {
391
+ const heading = useId();
392
+ const card = useRef(null);
393
+ const { id } = account;
394
+ useEffect(() => {
395
+ if (focusTarget?.id !== id) return;
396
+ card.current?.focus({ preventScroll: true });
397
+ card.current?.scrollIntoView({ block: 'nearest' });
398
+ }, [focusTarget, id]);
399
+ const loginActive = account.status === 'login' || account.busy === 'login';
400
+ const loginUrl = account.status === 'login' ? safeLoginUrl(account) : null;
401
+ const currentPending = pending?.id === id;
402
+ const pendingAction = currentPending ? pending.action : account.busy;
403
+ const running = Boolean(pendingAction || loginActive);
404
+ const cli = available[account.provider] === true;
405
+ const rowName = account.name || providers[account.provider] || t('unknown');
406
+ const stateKey = { new: 'new', login: 'loginStatus', ready: 'ready', error: 'error' }[account.status] || 'unknown';
407
+ function act(action, extra) { run(action, { id, ...extra }); }
408
+ return h('article', { className: 'dsa-card', ref: card, tabIndex: -1, 'aria-labelledby': heading },
409
+ h('header', { className: 'dsa-row dsa-spread' },
410
+ h('div', null, h('p', { className: 'dsa-meta' }, [account.number == null ? null : `#${account.number}`, providers[account.provider]].filter(Boolean).join(' · ')), h('h3', { id: heading }, rowName)),
411
+ h('span', { className: 'dsa-badge', 'data-status': account.status }, t(stateKey))),
412
+ !cli && h('p', { className: 'dsa-meta dsa-warn' }, t('noCli')),
413
+ h('div', { className: 'dsa-row' },
414
+ h(Button, {
415
+ role: 'switch', 'aria-checked': Boolean(account.enabled), 'aria-label': `${t('switchLabel')}: ${rowName}`,
416
+ className: 'dsa-switch', disabled: Boolean(pending) || (!account.enabled && (!cli || account.status !== 'ready' || account.testPassed !== true || running)),
417
+ onClick: event => account.enabled ? act('toggle', { enabled: false }) : begin('enable', id, event.currentTarget),
418
+ }, h('span', { className: 'dsa-switch-mark', 'aria-hidden': true }), t(account.enabled ? 'enabled' : 'disabled'))),
419
+ !account.enabled && cli && account.status === 'ready' && account.testPassed !== true && !running && h('p', { className: 'dsa-meta' }, t('gate')),
420
+ pendingAction && h('p', { role: 'status', className: 'dsa-meta' }, t(progress[pendingAction] || 'working')),
421
+ account.status === 'login' && h('p', { className: 'dsa-subtle' }, t('loginHelp')),
422
+ loginUrl && h('p', null, h('a', { href: loginUrl, target: '_blank', rel: 'noopener noreferrer' }, t('openSignIn'))),
423
+ account.note && h('p', { className: 'dsa-meta dsa-note', 'aria-live': 'polite' }, account.note),
424
+ h(Usage, { account, t }),
425
+ h('div', { className: 'dsa-row dsa-actions' },
426
+ loginActive ? h(Button, { disabled: Boolean(pending), onClick: () => act('cancel') }, t('stop')) :
427
+ h(Button, { variant: account.status === 'ready' ? undefined : 'primary', disabled: Boolean(pending) || !cli || running, onClick: () => act('login') }, t(account.status === 'ready' ? 'loginAgain' : 'login')),
428
+ h(Button, { disabled: Boolean(pending) || !cli || running || !['ready', 'error'].includes(account.status), onClick: () => act('refresh') }, t(account.provider === 'claude' ? 'verifySignIn' : 'refresh')),
429
+ h(Button, { disabled: Boolean(pending) || !cli || running || !['ready', 'error'].includes(account.status), onClick: () => act('test') }, t('test')),
430
+ h(Button, { disabled: Boolean(pending) || running, onClick: event => begin('rename', id, event.currentTarget) }, t('rename')),
431
+ h(Button, { variant: 'danger', disabled: Boolean(pending) || running, onClick: event => begin('remove', id, event.currentTarget) }, t('remove'))),
432
+ edit && h(Editor, { key: edit.kind, kind: edit.kind, account, available, pending: Boolean(pending), onSubmit: run, onClose: close, t }),
433
+ notice && h('p', { className: `dsa-note${notice.error ? ' dsa-error' : ''}`, role: notice.error ? 'alert' : 'status' }, notice.text));
434
+ }
435
+
436
+ function Panel({ t, usePanelTarget }) {
437
+ const requested = usePanelTarget();
438
+ const [added, setAdded] = useState(null);
439
+ const [snapshot, setSnapshot] = useState(null);
440
+ const [listError, setListError] = useState(null);
441
+ const [pending, setPending] = useState(null);
442
+ const [notice, setNotice] = useState(null);
443
+ const [edit, setEdit] = useState(null);
444
+ const [checkUntil, setCheckUntil] = useState(0);
445
+ const lifecycle = useRef(null);
446
+ const requestId = useRef(0);
447
+ const listRequest = useRef(null);
448
+ const actionLock = useRef(false);
449
+ const trigger = useRef(null);
450
+ const addButton = useRef(null);
451
+ const heading = useId();
452
+ const listHeading = useId();
453
+ const accounts = snapshot?.accounts || [];
454
+ const available = snapshot?.available || {};
455
+ const rapid = checkUntil > Date.now() || accounts.some(account => account.busy || account.status === 'login');
456
+ const hasProvider = Object.keys(providers).some(provider => available[provider] === true);
457
+
458
+ async function load(force = false) {
459
+ const signal = lifecycle.current?.signal;
460
+ if (!signal || signal.aborted) return;
461
+ if (listRequest.current?.signal === signal && !force) return;
462
+ const id = ++requestId.current;
463
+ const request = { id, signal };
464
+ listRequest.current = request;
465
+ const result = await call('list', {}, signal);
466
+ if (listRequest.current === request) listRequest.current = null;
467
+ if (!result || signal.aborted || id !== requestId.current) return;
468
+ if (!result.ok || !Array.isArray(result.accounts)) {
469
+ setListError(result.error ? { text: result.error } : { key: result.message || 'invalidResponse' });
470
+ return;
471
+ }
472
+ setListError(null);
473
+ setSnapshot({ accounts: result.accounts, available: result.available || {} });
474
+ if (result.accounts.some(account => account.busy || account.status === 'login')) setCheckUntil(0);
475
+ }
476
+ useEffect(() => {
477
+ const controller = new AbortController();
478
+ lifecycle.current = controller;
479
+ void load();
480
+ return () => controller.abort();
481
+ }, []);
482
+ useEffect(() => {
483
+ const timer = window.setInterval(() => {
484
+ if (document.visibilityState !== 'hidden' && !actionLock.current) void load();
485
+ }, rapid ? 1800 : 15000);
486
+ return () => window.clearInterval(timer);
487
+ }, [rapid]);
488
+
489
+ function begin(kind, id, button) {
490
+ if (actionLock.current) return;
491
+ trigger.current = button;
492
+ setNotice(null);
493
+ setEdit({ kind, id });
494
+ }
495
+ function close(focusFallback = false) {
496
+ setEdit(null);
497
+ const button = focusFallback ? addButton.current : trigger.current;
498
+ button?.focus();
499
+ trigger.current = null;
500
+ }
501
+ async function run(action, payload = {}) {
502
+ const signal = lifecycle.current?.signal;
503
+ if (!signal || signal.aborted || actionLock.current) return;
504
+ actionLock.current = true;
505
+ setPending({ action, id: payload.id });
506
+ setNotice(null);
507
+ let focusTarget;
508
+ try {
509
+ const result = await call(action, payload, signal);
510
+ if (!result || signal.aborted) return;
511
+ if (result.ok) {
512
+ setNotice({ id: action === 'remove' ? undefined : payload.id, key: success[action] });
513
+ if (['login', 'refresh', 'test', 'cancel'].includes(action)) setCheckUntil(Date.now() + 16000);
514
+ if ((edit?.kind === action || (edit?.kind === 'enable' && action === 'toggle')) && edit.id === payload.id) {
515
+ if (action === 'add' && result.account?.id) setAdded({ id: result.account.id, at: Date.now() });
516
+ else focusTarget = action === 'remove' ? addButton.current : trigger.current;
517
+ setEdit(null);
518
+ trigger.current = null;
519
+ }
520
+ } else {
521
+ setNotice({ id: payload.id, error: true, text: result.error, key: result.message });
522
+ }
523
+ await load(true);
524
+ } finally {
525
+ actionLock.current = false;
526
+ if (!signal.aborted) {
527
+ setPending(null);
528
+ if (focusTarget) window.requestAnimationFrame(() => { if (!signal.aborted) focusTarget.focus(); });
529
+ }
530
+ }
531
+ }
532
+ const feedback = notice && { error: notice.error, text: notice.text || t(notice.key) };
533
+ return h('section', { className: 'dsa-panel', 'aria-labelledby': heading }, h('style', null, styles),
534
+ h('div', { className: 'dsa-inner' },
535
+ h('header', { className: 'dsa-head' },
536
+ h('h1', { id: heading }, t('title')),
537
+ h('p', { className: 'dsa-subtle' }, t('intro')),
538
+ h('p', { className: 'dsa-meta' }, t('privacy')),
539
+ h('div', { className: 'dsa-toolbar' },
540
+ h('button', { type: 'button', ref: addButton, className: 'dsa-primary', disabled: Boolean(pending) || !hasProvider, onClick: event => begin('add', undefined, event.currentTarget) }, t('add')),
541
+ h(Button, { disabled: Boolean(pending) || !accounts.some(account => available[account.provider] && !account.busy && account.provider === 'codex' && account.status === 'ready'), onClick: () => run('refresh') }, t('refreshAll'))),
542
+ snapshot && !hasProvider && h('p', { className: 'dsa-meta dsa-warn' }, t('noProviders'))),
543
+ edit?.kind === 'add' && h(Editor, { key: 'add', kind: 'add', available, pending: Boolean(pending), onSubmit: run, onClose: () => close(), t }),
544
+ pending && pending.id === undefined && h('p', { role: 'status', className: 'dsa-subtle' }, t(progress[pending.action])),
545
+ feedback && notice.id === undefined && h('p', { className: `dsa-note${feedback.error ? ' dsa-error' : ''}`, role: feedback.error ? 'alert' : 'status' }, feedback.text),
546
+ listError && h('div', { className: 'dsa-message dsa-head' },
547
+ h('p', { role: 'alert', className: 'dsa-error dsa-note' }, `${t(snapshot ? 'staleList' : 'listError')} ${listError.text || t(listError.key)}`),
548
+ h('div', null, h(Button, { disabled: Boolean(pending), onClick: () => load(true) }, t('retry')))),
549
+ h('section', { className: 'dsa-list', 'aria-labelledby': listHeading },
550
+ h('h2', { id: listHeading }, t('accounts')),
551
+ !snapshot && !listError && h('p', { role: 'status', className: 'dsa-subtle' }, t('loading')),
552
+ snapshot && accounts.length === 0 && h('div', { className: 'dsa-message dsa-head' }, h('strong', null, t('empty')), h('p', { className: 'dsa-subtle' }, t('emptyHelp'))),
553
+ accounts.map(account => h(Account, {
554
+ account, available, key: account.id, t, pending, begin, close: () => close(), run, focusTarget: added && (!requested || added.at >= requested.at) ? added : requested,
555
+ edit: edit?.id === account.id ? edit : null,
556
+ notice: notice?.id === account.id ? feedback : null,
557
+ })))));
558
+ }
559
+
560
+ return {
561
+ inject: ['slots', 'locale', 'layout', 'sessions', 'uiWorkspace'],
562
+ apply(ctx) {
563
+ ctx.effect(() => ctx.locale.register(NS, { ru, en, zh: en }), 'subscription agents: locale');
564
+ const t = ctx.locale.bind(NS);
565
+ let panelTarget;
566
+ const listeners = new Set();
567
+ const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
568
+ const getTarget = () => panelTarget;
569
+ const usePanelTarget = () => React.useSyncExternalStore(subscribe, getTarget);
570
+ const openPanel = id => {
571
+ panelTarget = { id, at: Date.now() };
572
+ for (const listener of listeners) listener();
573
+ ctx.layout.selectPanel(PANEL);
574
+ };
575
+ ctx.slots.inject('main', () => ctx.slots.register({
576
+ name: 'main', key: PANEL, locale: NS, inject: () => ({ usePanelTarget }),
577
+ }, Panel));
578
+
579
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
580
+ name: 'sidebar.footer.action', id: `${PANEL}.usage`, locale: NS, inject: () => ({ openPanel }),
581
+ }, SidebarUsage));
582
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
583
+ name: 'sidebar.panellist', id: PANEL, order: 80, label: () => t('panel'), locale: NS,
584
+ }, PanelIcon));
585
+ },
586
+ };
587
+ },
588
+ });