@celljs/ta-cron 4.8.0 → 4.9.1

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/web-src/i18n.ts DELETED
@@ -1,175 +0,0 @@
1
- const EN = {
2
- title: 'Scheduled',
3
- newTask: 'New task',
4
- editTask: 'Edit task',
5
- count: '{count} tasks',
6
- runningCount: '{count} running',
7
- emptyTitle: 'Let Ta work on a schedule',
8
- emptyHint: 'Each run is a new conversation; you get the summary.',
9
- example1: 'Sum up yesterday’s commits',
10
- example2: 'Check that CI passes',
11
- example3: 'Write the daily report',
12
- next: 'in {time}',
13
- nextAt: 'Next {time}',
14
- running: 'Running…',
15
- paused: 'Paused',
16
- done: 'Done',
17
- runNow: 'Run now',
18
- edit: 'Edit',
19
- delete: 'Delete',
20
- confirmDelete: 'Delete {name}?',
21
- confirmDeleteMessage: 'Its runs go too; their conversations stay.',
22
- enable: 'On',
23
- prompt: 'What should Ta do?',
24
- promptPlaceholder: 'For example: check whether CI on main passes; if not, find out why',
25
- name: 'Name',
26
- namePlaceholder: 'Optional',
27
- when: 'When',
28
- repeat: 'Repeat',
29
- once: 'Once',
30
- every: 'Every',
31
- daily: 'Daily',
32
- weekdays: 'Weekdays',
33
- weekly: 'Weekly',
34
- custom: 'Cron',
35
- minutes: 'minutes',
36
- hours: 'hours',
37
- days: 'days',
38
- directory: 'Directory',
39
- notify: 'Tell me',
40
- notifyDefault: 'Default',
41
- notifyAlways: 'Every run',
42
- notifyError: 'When it fails',
43
- notifyNever: 'Never',
44
- model: 'Model',
45
- modelPlaceholder: 'Default model',
46
- modelDefaultNamed: 'Default ({name})',
47
- thinking: 'Thinking',
48
- searchModels: 'Search {count} models',
49
- noModels: 'No model matches.',
50
- more: 'More',
51
- cancel: 'Cancel',
52
- save: 'Save',
53
- create: 'Create',
54
- preview: 'Next run {time}',
55
- noNext: 'No next run',
56
- runs: 'Runs',
57
- noRuns: 'No runs yet',
58
- byHand: 'by hand',
59
- openChat: 'Open conversation',
60
- noChat: 'This run has no conversation.',
61
- success: 'Done',
62
- error: 'Failed',
63
- missed: 'Missed',
64
- interrupted: 'The Ta service stopped during the run.',
65
- timeout: 'The run took too long and was stopped.',
66
- missedText: 'The Ta service was not running at its time.',
67
- started: 'Started {name}',
68
- finished: '{name} is done',
69
- failed: '{name} failed',
70
- created: 'Scheduled',
71
- updated: 'Updated',
72
- enabled: 'Turned on',
73
- disabled: 'Turned off',
74
- removed: 'Removed {names}',
75
- removedNone: 'Nothing removed',
76
- noTasks: 'No scheduled tasks yet. Try /loop 30m <prompt>.',
77
- show: 'Show',
78
- failedAction: 'Could not do it: {message}',
79
- help: 'Scheduled tasks',
80
- serviceNeeded: 'Scheduled tasks run in the Ta service.',
81
- };
82
-
83
- export type Words = { readonly [K in keyof typeof EN]: string };
84
-
85
- const ZH: Words = {
86
- title: '定时任务',
87
- newTask: '新建任务',
88
- editTask: '编辑任务',
89
- count: '{count} 个任务',
90
- runningCount: '{count} 个运行中',
91
- emptyTitle: '让 Ta 按时干活',
92
- emptyHint: '每次运行都是一个新对话,结束后给你看总结。',
93
- example1: '汇总昨天的提交',
94
- example2: '检查 CI 是否通过',
95
- example3: '写今天的日报',
96
- next: '{time}后',
97
- nextAt: '下次 {time}',
98
- running: '运行中…',
99
- paused: '已暂停',
100
- done: '已完成',
101
- runNow: '立即运行',
102
- edit: '编辑',
103
- delete: '删除',
104
- confirmDelete: '删除“{name}”?',
105
- confirmDeleteMessage: '它的运行记录一起删除;对话保留。',
106
- enable: '启用',
107
- prompt: '要 Ta 做什么?',
108
- promptPlaceholder: '例如:检查 main 分支的 CI 是否通过,没通过就查明原因',
109
- name: '名字',
110
- namePlaceholder: '可不填',
111
- when: '时间',
112
- repeat: '重复',
113
- once: '一次',
114
- every: '每隔',
115
- daily: '每天',
116
- weekdays: '工作日',
117
- weekly: '每周',
118
- custom: 'Cron',
119
- minutes: '分钟',
120
- hours: '小时',
121
- days: '天',
122
- directory: '目录',
123
- notify: '通知我',
124
- notifyDefault: '默认',
125
- notifyAlways: '每次运行',
126
- notifyError: '失败时',
127
- notifyNever: '不通知',
128
- model: '模型',
129
- modelPlaceholder: '默认模型',
130
- modelDefaultNamed: '默认({name})',
131
- thinking: '思考级别',
132
- searchModels: '搜索 {count} 个模型',
133
- noModels: '没有匹配的模型。',
134
- more: '更多',
135
- cancel: '取消',
136
- save: '保存',
137
- create: '创建',
138
- preview: '下次运行 {time}',
139
- noNext: '没有下次运行',
140
- runs: '运行记录',
141
- noRuns: '还没有运行过',
142
- byHand: '手动',
143
- openChat: '打开对话',
144
- noChat: '这次运行没有对话。',
145
- success: '完成',
146
- error: '失败',
147
- missed: '错过',
148
- interrupted: 'Ta 服务在运行中途停止了。',
149
- timeout: '运行时间太长,已停止。',
150
- missedText: '到点时 Ta 服务没有运行。',
151
- started: '已开始运行“{name}”',
152
- finished: '“{name}”已完成',
153
- failed: '“{name}”运行失败',
154
- created: '已创建定时任务',
155
- updated: '已更新',
156
- enabled: '已启用',
157
- disabled: '已暂停',
158
- removed: '已删除 {names}',
159
- removedNone: '没有删除任何任务',
160
- noTasks: '还没有定时任务。试试 /loop 30m <要做的事>。',
161
- show: '查看',
162
- failedAction: '操作失败:{message}',
163
- help: '定时任务',
164
- serviceNeeded: '定时任务在 Ta 服务里运行。',
165
- };
166
-
167
- export namespace CronWords {
168
- export function of(language: string): Words {
169
- return language === 'zh-CN' ? ZH : EN;
170
- }
171
-
172
- export function format(text: string, values: Record<string, string | number>): string {
173
- return text.replace(/\{(\w+)\}/g, (whole, key: string) => (key in values ? String(values[key]) : whole));
174
- }
175
- }
package/web-src/index.tsx DELETED
@@ -1,35 +0,0 @@
1
- import type { WebExtensionAPI } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
- import { REPLY_TYPE } from './cron-protocol';
3
- import { watchRuns } from './notifier';
4
- import { bindPage, CronClient, icon, t } from './page';
5
- // biome-ignore lint/correctness/noUnusedImports: the JSX below compiles to React.createElement (jsxFactory)
6
- import { bind, React } from './react';
7
- import { ReplyMessage } from './reply';
8
- import { injectStyle } from './style';
9
- import { TasksPage } from './tasks-view';
10
-
11
- /**
12
- * The page of the scheduled tasks in the navigation, the answers of the commands in conversations, and
13
- * a notice when a run ends. The tasks run in the Ta service (host.ts), and the commands and Ta's tool are
14
- * in the pi extension (extension.ts): this only shows them and changes them.
15
- */
16
- export default function activate(pi: WebExtensionAPI): () => void {
17
- bind(pi.React);
18
- bindPage(pi);
19
- const removeStyle = injectStyle();
20
- const client = new CronClient(pi);
21
- client.start();
22
- pi.registerView('tasks', {
23
- title: () => t('title'),
24
- icon: icon('AlarmClock'),
25
- render: () => <TasksPage client={client} />,
26
- order: 70,
27
- });
28
- pi.registerMessageRenderer(REPLY_TYPE, ReplyMessage);
29
- const stopWatching = watchRuns();
30
- return () => {
31
- stopWatching();
32
- client.dispose();
33
- removeStyle();
34
- };
35
- }
@@ -1,32 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { type Models, ModelUtil } from './model-picker';
3
-
4
- describe('ModelUtil', () => {
5
- const models: Models = {
6
- refs: ['anthropic/claude-sonnet-5', 'anthropic/claude-opus-5', 'openai/gpt-6', 'agents/codex'],
7
- names: { 'anthropic/claude-sonnet-5': 'Claude Sonnet 5', 'agents/codex': 'Codex' },
8
- };
9
- const refs = (query: string, keep?: string) => ModelUtil.groups(models, query, keep).flatMap(group => group.refs);
10
-
11
- it('groups the models by provider, in the order of the settings', () => {
12
- expect(ModelUtil.groups(models, '').map(group => [group.provider, group.refs.length])).toEqual([
13
- ['anthropic', 2],
14
- ['openai', 1],
15
- ['agents', 1],
16
- ]);
17
- });
18
-
19
- it('finds models by every word of the query in their name, id or provider', () => {
20
- expect(refs('sonnet')).toEqual(['anthropic/claude-sonnet-5']);
21
- expect(refs('CLAUDE 5 opus')).toEqual(['anthropic/claude-opus-5']);
22
- expect(refs('openai')).toEqual(['openai/gpt-6']);
23
- expect(refs('codex')).toEqual(['agents/codex']);
24
- expect(refs('gemini')).toEqual([]);
25
- });
26
-
27
- it('keeps a model of the task that is not offered now, first', () => {
28
- expect(refs('', 'old/model-1')[0]).toBe('old/model-1');
29
- expect(refs('', 'openai/gpt-6')).toHaveLength(4);
30
- expect(ModelUtil.name(models, 'openai/gpt-6')).toBe('gpt-6');
31
- });
32
- });
@@ -1,227 +0,0 @@
1
- import { icon, pi, t } from './page';
2
- import { React } from './react';
3
-
4
- /** The models the settings of a directory offer. */
5
- export interface Models {
6
- /** `<provider>/<model id>` of the models with credentials, pi packages' included. */
7
- refs: string[];
8
- names: Record<string, string>;
9
- /** What the settings start a conversation on. */
10
- fallback?: string;
11
- }
12
-
13
- export interface ModelGroup {
14
- provider: string;
15
- refs: string[];
16
- }
17
-
18
- /** The height of the list at most, and the room it wants below the field before it opens above it. */
19
- const LIST_MAX = 320;
20
-
21
- export namespace ModelUtil {
22
- export function name(models: Models | undefined, ref: string): string {
23
- return models?.names[ref] ?? ref.slice(ref.indexOf('/') + 1);
24
- }
25
-
26
- export function provider(ref: string): string {
27
- return ref.slice(0, ref.indexOf('/'));
28
- }
29
-
30
- /**
31
- * The models whose name, id or provider holds every word of the query, by provider in the order of the
32
- * settings; `keep`, a model of the task that is not offered now, comes first so that it stays.
33
- */
34
- export function groups(models: Models | undefined, query: string, keep?: string): ModelGroup[] {
35
- const refs = models?.refs ?? [];
36
- const all = keep && !refs.includes(keep) ? [keep, ...refs] : refs;
37
- const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
38
- const groups = new Map<string, string[]>();
39
- for (const ref of all) {
40
- const text = `${name(models, ref)} ${ref}`.toLowerCase();
41
- if (words.every(word => text.includes(word))) {
42
- const key = provider(ref);
43
- groups.set(key, [...(groups.get(key) ?? []), ref]);
44
- }
45
- }
46
- return [...groups].map(([key, list]) => ({ provider: key, refs: list }));
47
- }
48
- }
49
-
50
- /** The models the settings of the directory offer, read again when it changes. */
51
- export function useModels(cwd: string): Models | undefined {
52
- const [models, setModels] = React.useState<Models>();
53
- React.useEffect(() => {
54
- let live = true;
55
- pi.settings.getSettings(cwd || undefined).then(
56
- snapshot => {
57
- const fallback = snapshot.project.model ?? snapshot.user.model;
58
- live &&
59
- setModels({
60
- refs: snapshot.models,
61
- names: snapshot.modelNames ?? {},
62
- fallback: typeof fallback === 'string' && fallback ? fallback : undefined,
63
- });
64
- },
65
- () => live && setModels({ refs: [], names: {} }),
66
- );
67
- return () => {
68
- live = false;
69
- };
70
- }, [cwd]);
71
- return models;
72
- }
73
-
74
- /**
75
- * A field that opens a list of the models with a search box on top: typing narrows it by name, id or
76
- * provider; arrows and Enter pick, Escape closes the list (not the dialog). `''` is the default of the settings.
77
- */
78
- export function ModelPicker({ models, value, onChange }: { models: Models | undefined; value: string; onChange(value: string): void }) {
79
- const [open, setOpen] = React.useState(false);
80
- const [query, setQuery] = React.useState('');
81
- const [active, setActive] = React.useState(0);
82
- const [place, setPlace] = React.useState<React.CSSProperties>();
83
- const field = React.useRef<HTMLButtonElement>(null);
84
- const popup = React.useRef<HTMLDivElement>(null);
85
- const list = React.useRef<HTMLDivElement>(null);
86
- const groups = ModelUtil.groups(models, query, value || undefined);
87
- // The default first while nothing is typed: '' stands for it.
88
- const choices = [...(query.trim() ? [] : ['']), ...groups.flatMap(group => group.refs)];
89
- const fallback = models?.fallback ? t('modelDefaultNamed', { name: ModelUtil.name(models, models.fallback) }) : t('modelPlaceholder');
90
- const label = value ? ModelUtil.name(models, value) : fallback;
91
-
92
- const show = () => {
93
- const rect = field.current?.getBoundingClientRect();
94
- if (!rect) {
95
- return;
96
- }
97
- const below = window.innerHeight - rect.bottom;
98
- const up = below < LIST_MAX + 60 && rect.top > below;
99
- setPlace({ left: rect.left, width: rect.width, ...(up ? { bottom: window.innerHeight - rect.top + 4 } : { top: rect.bottom + 4 }) });
100
- setQuery('');
101
- setActive(Math.max(0, choices.indexOf(value)));
102
- setOpen(true);
103
- };
104
- const pick = (ref: string) => {
105
- onChange(ref);
106
- setOpen(false);
107
- field.current?.focus();
108
- };
109
- React.useEffect(() => {
110
- if (!open) {
111
- return;
112
- }
113
- const close = (event: Event) => {
114
- const target = event.target as Node;
115
- if (!popup.current?.contains(target) && !field.current?.contains(target)) {
116
- setOpen(false);
117
- }
118
- };
119
- const away = () => setOpen(false);
120
- document.addEventListener('pointerdown', close, true);
121
- window.addEventListener('resize', away);
122
- return () => {
123
- document.removeEventListener('pointerdown', close, true);
124
- window.removeEventListener('resize', away);
125
- };
126
- }, [open]);
127
- React.useEffect(() => {
128
- list.current?.querySelector('[data-active="true"]')?.scrollIntoView({ block: 'nearest' });
129
- }, [active, open]);
130
-
131
- const onKey = (event: React.KeyboardEvent) => {
132
- if (event.key === 'Escape') {
133
- // The dialog hears Escape on the document: it closes only the list.
134
- event.stopPropagation();
135
- setOpen(false);
136
- field.current?.focus();
137
- } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
138
- event.preventDefault();
139
- const step = event.key === 'ArrowDown' ? 1 : -1;
140
- setActive(index => (choices.length ? (index + step + choices.length) % choices.length : 0));
141
- } else if (event.key === 'Enter') {
142
- event.preventDefault();
143
- if (choices[active] !== undefined) {
144
- pick(choices[active]);
145
- }
146
- }
147
- };
148
- const Check = icon('Check');
149
- const Search = icon('Search');
150
- const Chevron = icon('ChevronDown');
151
- const row = (ref: string, text: string, detail?: string) => {
152
- const index = choices.indexOf(ref);
153
- return (
154
- <button
155
- key={ref || 'default'}
156
- type="button"
157
- role="option"
158
- aria-selected={ref === value}
159
- data-active={index === active}
160
- className="tcr-option"
161
- onMouseMove={() => setActive(index)}
162
- onClick={() => pick(ref)}
163
- >
164
- <span className="tcr-option-check">{ref === value && <Check size={14} />}</span>
165
- <span className="tcr-option-name">{text}</span>
166
- {detail && <span className="tcr-option-detail">{detail}</span>}
167
- </button>
168
- );
169
- };
170
- return (
171
- <div className="tcr-picker">
172
- <button
173
- type="button"
174
- className="tcr-input tcr-select"
175
- ref={field}
176
- disabled={!models}
177
- title={value || undefined}
178
- aria-haspopup="listbox"
179
- aria-expanded={open}
180
- onClick={() => (open ? setOpen(false) : show())}
181
- onKeyDown={event => {
182
- if (!open && (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ')) {
183
- event.preventDefault();
184
- show();
185
- }
186
- }}
187
- >
188
- <span className={value ? '' : 'tcr-muted'}>{label}</span>
189
- <Chevron size={15} />
190
- </button>
191
- {open && (
192
- <div className="tcr-popup" ref={popup} style={place}>
193
- <div className="tcr-search">
194
- <Search size={14} />
195
- <input
196
- value={query}
197
- placeholder={t('searchModels', { count: models?.refs.length ?? 0 })}
198
- // biome-ignore lint/a11y/noAutofocus: the list opened to be searched
199
- autoFocus
200
- onKeyDown={onKey}
201
- onChange={event => {
202
- setQuery(event.target.value);
203
- setActive(0);
204
- }}
205
- />
206
- </div>
207
- <div className="tcr-options" ref={list} role="listbox">
208
- {!query.trim() && row('', fallback)}
209
- {groups.map(group => (
210
- <div key={group.provider}>
211
- <div className="tcr-option-group">{group.provider}</div>
212
- {group.refs.map(ref =>
213
- row(
214
- ref,
215
- ModelUtil.name(models, ref),
216
- ModelUtil.name(models, ref) === ref.slice(ref.indexOf('/') + 1) ? undefined : ref.slice(ref.indexOf('/') + 1),
217
- ),
218
- )}
219
- </div>
220
- ))}
221
- {choices.length === 0 && <div className="tcr-option-empty">{t('noModels')}</div>}
222
- </div>
223
- </div>
224
- )}
225
- </div>
226
- );
227
- }
@@ -1,47 +0,0 @@
1
- import { type FinishedRun, Keys } from './cron-protocol';
2
- import { PAGE, pi, t } from './page';
3
-
4
- /** A run that ended longer ago than this is old news: a page that opens later does not tell of it. */
5
- const FRESH_MS = 2 * 60_000;
6
-
7
- /**
8
- * Tells the user when a run ends, as its task's notify level says: a notice of the page, and a notice of
9
- * the system while the page is hidden (once the user allowed them). Each page tells of each run once.
10
- */
11
- export function watchRuns(): () => void {
12
- const told = new Set<string>();
13
- let ready = false;
14
- const tell = async () => {
15
- const finished = (await pi.storage.get<FinishedRun>(Keys.LATEST).catch(() => undefined)) as FinishedRun | undefined;
16
- const run = finished?.run;
17
- if (!run || told.has(run.id)) {
18
- return;
19
- }
20
- told.add(run.id);
21
- const ended = run.endedAt ? new Date(run.endedAt).getTime() : 0;
22
- if (!ready || !finished.notify || Date.now() - ended > FRESH_MS) {
23
- return;
24
- }
25
- const failed = run.status !== 'success';
26
- const title = t(failed ? 'failed' : 'finished', { name: finished.taskName });
27
- pi.ui.notify(title, failed ? 'error' : 'info');
28
- if (typeof document !== 'undefined' && document.hidden && typeof Notification !== 'undefined' && Notification.permission === 'granted') {
29
- const body = (run.error ?? run.summary ?? '').split('\n')[0].slice(0, 160);
30
- const notice = new Notification(title, { body, tag: run.id });
31
- notice.onclick = () => {
32
- window.focus();
33
- pi.ui.showView(PAGE);
34
- notice.close();
35
- };
36
- }
37
- };
38
- // The first read is what ended before the page opened, and lets the page hear the key change.
39
- void tell().finally(() => {
40
- ready = true;
41
- });
42
- return pi.storage.onChange(keys => {
43
- if (keys.includes(Keys.LATEST)) {
44
- void tell();
45
- }
46
- });
47
- }
package/web-src/page.ts DELETED
@@ -1,126 +0,0 @@
1
- import type { WebExtensionAPI, WebIcon } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
- import { Keys, NAME, type Run, type Task } from './cron-protocol';
3
- import { CronWords, type Words } from './i18n';
4
-
5
- /** The API of the page, bound once by `activate`. */
6
- export let pi: WebExtensionAPI;
7
-
8
- export const PAGE = `${NAME}/tasks`;
9
-
10
- export function bindPage(api: WebExtensionAPI): void {
11
- pi = api;
12
- }
13
-
14
- export function t(key: keyof Words, values: Record<string, string | number> = {}): string {
15
- return CronWords.format(CronWords.of(pi.ui.language)[key], values);
16
- }
17
-
18
- /** An icon of the page, or an empty one when the page is older than the icon. */
19
- export function icon(name: string): WebIcon {
20
- return pi.ui.icons[name] ?? pi.ui.icons.Square;
21
- }
22
-
23
- export function message(error: unknown): string {
24
- return error instanceof Error ? error.message : String(error);
25
- }
26
-
27
- /** `2 hours`, `5 分钟`: how long until a time, roughly. */
28
- export function until(time: number, now = Date.now()): string {
29
- const minutes = Math.max(1, Math.round((time - now) / 60_000));
30
- const zh = pi.ui.language === 'zh-CN';
31
- const [amount, unit] = minutes < 60 ? [minutes, 'minute'] : minutes < 48 * 60 ? [Math.round(minutes / 60), 'hour'] : [Math.round(minutes / 1440), 'day'];
32
- if (zh) {
33
- return `${amount} ${{ minute: '分钟', hour: '小时', day: '天' }[unit]}`;
34
- }
35
- return `${amount} ${unit}${amount === 1 ? '' : 's'}`;
36
- }
37
-
38
- export function basename(path: string): string {
39
- return (
40
- path
41
- .replace(/[\\/]+$/, '')
42
- .split(/[\\/]/)
43
- .pop() || path
44
- );
45
- }
46
-
47
- interface State {
48
- tasks: Task[];
49
- loaded: boolean;
50
- /** By task id, its runs once asked for. */
51
- runs: Record<string, Run[]>;
52
- }
53
-
54
- /** The tasks of the scheduler, read again when the data of the package changes. */
55
- export class CronClient {
56
- state: State = { tasks: [], loaded: false, runs: {} };
57
- protected readonly listeners = new Set<() => void>();
58
- protected stop?: () => void;
59
-
60
- constructor(protected readonly api: WebExtensionAPI) {}
61
-
62
- start(): void {
63
- this.stop = this.api.storage.onChange(keys => {
64
- if (keys.includes(Keys.TASKS)) {
65
- void this.load();
66
- }
67
- for (const key of keys) {
68
- const id = key.startsWith('runs/') ? key.slice(5) : undefined;
69
- if (id && this.state.runs[id]) {
70
- void this.loadRuns(id);
71
- }
72
- }
73
- });
74
- void this.load();
75
- }
76
-
77
- dispose(): void {
78
- this.stop?.();
79
- this.listeners.clear();
80
- }
81
-
82
- subscribe(listener: () => void): () => void {
83
- this.listeners.add(listener);
84
- return () => this.listeners.delete(listener);
85
- }
86
-
87
- async load(): Promise<void> {
88
- // Read through the storage too, so that its changes are heard.
89
- await this.api.storage.get(Keys.TASKS).catch(() => undefined);
90
- const tasks = await this.api.callHost<Task[]>('list');
91
- this.set({ tasks, loaded: true });
92
- }
93
-
94
- async loadRuns(taskId: string): Promise<void> {
95
- await this.api.storage.get(Keys.runs(taskId)).catch(() => undefined);
96
- const runs = await this.api.callHost<Run[]>('runs', taskId);
97
- this.set({ runs: { ...this.state.runs, [taskId]: runs } });
98
- }
99
-
100
- call<T>(method: string, ...params: unknown[]): Promise<T> {
101
- return this.api.callHost<T>(method, ...params);
102
- }
103
-
104
- protected set(change: Partial<State>): void {
105
- this.state = { ...this.state, ...change };
106
- for (const listener of this.listeners) {
107
- listener();
108
- }
109
- }
110
- }
111
-
112
- /** Shows the conversation of a run, opened on the server when it is not open. */
113
- export async function openRun(run: Run): Promise<void> {
114
- if (!run.sessionFile) {
115
- pi.ui.notify(t('noChat'), 'warning');
116
- return;
117
- }
118
- try {
119
- const open = (await pi.server.listSessions()).find(session => session.sessionFile === run.sessionFile);
120
- const sessionId = open?.sessionId ?? (await pi.server.openSession({ cwd: run.cwd, sessionFile: run.sessionFile, group: NAME })).sessionId;
121
- await pi.switchSession(sessionId);
122
- pi.ui.showView('');
123
- } catch (error) {
124
- pi.ui.notify(t('failedAction', { message: message(error) }), 'error');
125
- }
126
- }
package/web-src/react.ts DELETED
@@ -1,11 +0,0 @@
1
- import type * as ReactModule from 'react';
2
-
3
- /**
4
- * The React of the page, which a web extension cannot import: `activate` binds it before anything
5
- * renders. The JSX of this package compiles to `React.createElement` (tsconfig.json).
6
- */
7
- export let React: typeof ReactModule;
8
-
9
- export function bind(react: typeof ReactModule): void {
10
- React = react;
11
- }