ai-home-cli 0.1.0 → 0.1.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/README.md CHANGED
@@ -101,7 +101,9 @@ JSVision даёт `enter` без shift, расширенный протокол
101
101
  оставается одной строкой, многострочный ввод — следующий шаг библиотеки.
102
102
 
103
103
  Клавиши: `F10` — меню, `Alt+Р`/`Alt+О`/`Alt+К` — вкладки, `Alt+1` — навигатор,
104
- `Tab` — переход фокуса, `↑/↓` — выбор, `Enter` — действие, `Ctrl+K` — поиск по чатам,
104
+ `Tab` — переход фокуса, `↑/↓` — выбор, `Enter` — действие, `Ctrl+K` — поиск по чатам
105
+ (`Ctrl+G` переключает охват: текущий проект ↔ все проекты; выбор переживает закрытие
106
+ окна поиска, `PgUp/PgDn` — страницы выдачи, `Enter` — открыть, `Esc` — закрыть),
105
107
  `Ctrl+U` — очередь, `Ctrl+N` — новый чат, `Ctrl+T` — тема, `Ctrl+F` — фильтр списка,
106
108
  `F1` — справка по контексту. Мышь: клик по строке — тот же выбор, что клавиатурой,
107
109
  двойной клик открывает, колесо над списком листает его, над лентой — прокручивает.
@@ -27,6 +27,16 @@ export class ConnectionError extends ApiError {
27
27
  super(0, message);
28
28
  }
29
29
  }
30
+ /**
31
+ * Ответ сервера пришёл, но не той формы (например, у поиска нет items/complete).
32
+ * Отдельный вид, хотя status тоже 0: «нет связи» и «сервер ответил не то» — разные
33
+ * отказы, и футер не должен называть второй первым (R-CS-6).
34
+ */
35
+ export class InvalidResponseError extends ApiError {
36
+ constructor(message) {
37
+ super(0, message);
38
+ }
39
+ }
30
40
  /** mode нового чата — единственный, который просит CLI (§4.3). */
31
41
  const NEW_CHAT_MODE = 'acceptEdits';
32
42
  export class ApiClient {
@@ -82,6 +92,30 @@ export class ApiClient {
82
92
  async chatHistory(token, id) {
83
93
  return await this.readHistory('GET', `/chats/${enc(id)}/history`, token);
84
94
  }
95
+ /**
96
+ * GET /api/chats/search — поиск по названиям и сообщениям (CS-4). Abort доходит до
97
+ * сети: его сигнал уходит в fetch, а отмена не превращается в ConnectionError —
98
+ * вызывающий различает «отменили» и «нет связи».
99
+ */
100
+ async searchChats(token, params, signal) {
101
+ const query = new URLSearchParams();
102
+ query.set('q', params.q);
103
+ if (typeof params.projectId === 'string' && params.projectId.length > 0)
104
+ query.set('projectId', params.projectId);
105
+ if (params.global === true)
106
+ query.set('global', 'true');
107
+ if (params.archived !== undefined)
108
+ query.set('archived', params.archived);
109
+ if (params.limit !== undefined)
110
+ query.set('limit', String(params.limit));
111
+ if (typeof params.cursor === 'string' && params.cursor.length > 0)
112
+ query.set('cursor', params.cursor);
113
+ const data = await this.request('GET', `/chats/search?${query.toString()}`, undefined, token, signal);
114
+ if (!Array.isArray(data?.items) || typeof data.complete !== 'boolean') {
115
+ throw new InvalidResponseError('Сервер вернул неполный ответ поиска.');
116
+ }
117
+ return data;
118
+ }
85
119
  /** GET /api/personas?scope=context[&projectId=…] — персоны текущего контекста. */
86
120
  async personas(token, projectId) {
87
121
  const query = projectId !== undefined ? `?scope=context&projectId=${enc(projectId)}` : '?scope=context';
@@ -103,7 +137,7 @@ export class ApiClient {
103
137
  }
104
138
  return payload;
105
139
  }
106
- async request(method, path, body, token) {
140
+ async request(method, path, body, token, signal) {
107
141
  const headers = { accept: 'application/json' };
108
142
  if (body !== undefined)
109
143
  headers['content-type'] = 'application/json';
@@ -115,9 +149,13 @@ export class ApiClient {
115
149
  method,
116
150
  headers,
117
151
  body: body === undefined ? undefined : JSON.stringify(body),
152
+ ...(signal !== undefined ? { signal } : {}),
118
153
  });
119
154
  }
120
- catch {
155
+ catch (err) {
156
+ // Отмена — не сетевая ошибка: её видит вызывающий, а не текст «нет связи».
157
+ if (signal?.aborted === true)
158
+ throw err;
121
159
  // Текст сетевой ошибки fetch не содержит тела запроса — ни пароля, ни токена.
122
160
  // «Исход неизвестен» — часть смысла: после обрыва непонятно, дошёл ли запрос,
123
161
  // и сам он не повторяется (§4.4).
@@ -21,6 +21,7 @@ import { PERSONAL_SCOPE_KEY } from "../../catalog/store.js";
21
21
  import { TuiActions } from "../actions.js";
22
22
  import { SnapshotBinding } from "../snapshot-binding.js";
23
23
  import { bindCatalog } from "./catalog-adapter.js";
24
+ import { SearchRows, SearchSession, searchFooterText } from "./search.js";
24
25
  import { createFeedScroller } from "./feed-view.js";
25
26
  import { aiHomeThemes } from "./theme.js";
26
27
  import { JV_COMMAND_NAMES, JvCommands, jvKeymap, jvMenuBar, statusItemsFor } from "./commands.js";
@@ -115,6 +116,37 @@ class NavFilterInput extends Input {
115
116
  super.onEvent(ev);
116
117
  }
117
118
  }
119
+ /**
120
+ * Dialog поиска: фокус остаётся в поле ввода (набор не рвётся), а навигация по выдаче
121
+ * приходит сюда и уходит в SearchRows. ↑/↓/PgUp/PgDn не потребляет Input (это не motion
122
+ * однострочного редактора), Enter он тоже не потребляет — все пять доходят до Dialog'а.
123
+ * Ctrl+G ловит keymap цикла (глобально, и в открытом поиске тоже) — командой jv.search.scope.
124
+ */
125
+ class SearchDialog extends Dialog {
126
+ /** Навигация по выдаче: up/down/pageup/pagedown/enter — решение за владельцем списка. */
127
+ onNav = undefined;
128
+ /** Ctrl+G: во время модалки общий command sink цикла молчит, команду ловит сам диалог. */
129
+ onToggleScope = undefined;
130
+ onEvent(ev) {
131
+ const inner = ev.event;
132
+ // Команда охвата приезжает из keymap уже как command-событие; commandSink цикла во время
133
+ // модалки пропускается (event-loop: «handlers stay dormant during a modal»), поэтому
134
+ // единственный слушатель здесь — сам диалог.
135
+ if (inner.type === 'command' && inner.command === JvCommands.searchScope) {
136
+ ev.handled = true;
137
+ this.onToggleScope?.();
138
+ return;
139
+ }
140
+ if (inner.type === 'key' && !inner.ctrl && !inner.alt && !inner.shift) {
141
+ if (inner.key === 'up' || inner.key === 'down' || inner.key === 'pageup' || inner.key === 'pagedown' || inner.key === 'enter') {
142
+ ev.handled = true;
143
+ this.onNav?.(inner.key);
144
+ return;
145
+ }
146
+ }
147
+ super.onEvent(ev);
148
+ }
149
+ }
118
150
  /**
119
151
  * Окно экрана B: внешний вход Esc (замечание ревью e07e03a1). preProcess ставит его
120
152
  * первым в outer-sweep: пока модалки нет, сырой Esc доходит до окна раньше любой
@@ -209,6 +241,10 @@ export class JvApp {
209
241
  statusBusy = false;
210
242
  permissionOpen = false;
211
243
  modalOpen = false;
244
+ /** Открытый поиск: Ctrl+G бьёт в него, а не только в охват следующего Ctrl+K. */
245
+ activeSearch = null;
246
+ /** Последнее нажатие Ctrl+G переживает закрытие диалога и задаёт охват следующего. */
247
+ searchScope = 'current';
212
248
  /** Строка фильтра навигатора: по ней «Esc Очистить» опознаёт фокус на фильтре. */
213
249
  navFilterInput = null;
214
250
  /** Программная правка черновика (clear/restore): её не считать вводом человека. */
@@ -557,6 +593,15 @@ export class JvApp {
557
593
  };
558
594
  handle(JvCommands.newChat, () => { void this.actions.runCommand('/new', []); });
559
595
  handle(JvCommands.search, () => { void this.openSearchDialog(); });
596
+ // Ctrl+G: внутри открытого поиска — перезапрос его выдачи, вне — охват следующего Ctrl+K.
597
+ handle(JvCommands.searchScope, () => {
598
+ if (this.activeSearch !== null) {
599
+ this.activeSearch.toggleScope();
600
+ this.searchScope = this.activeSearch.scope;
601
+ return;
602
+ }
603
+ this.searchScope = this.searchScope === 'current' ? 'global' : 'current';
604
+ });
560
605
  handle(JvCommands.queue, () => { this.tabView.select(1); });
561
606
  handle(JvCommands.stop, () => { void this.actions.interrupt(); });
562
607
  handle(JvCommands.navigator, () => { this.openNavigator(); });
@@ -681,36 +726,64 @@ export class JvApp {
681
726
  loop.focusInto(chats);
682
727
  }
683
728
  }
729
+ /**
730
+ * Поиск по чатам (CS-6 на JSVision): мгновенный title-fallback из каталога, удалённый
731
+ * запрос с debounce, Ctrl+G — охват (переживает закрытие), PgUp/PgDn — страницы и
732
+ * nextCursor, ↑/↓ — выбор без потери фокуса композера, Enter — открыть, Esc — закрыть.
733
+ * Состояние и запрос — в SearchSession; здесь только сборка Dialog'а и его сигналы.
734
+ */
684
735
  async openSearchDialog() {
685
736
  if (this.modalOpen)
686
737
  return;
687
738
  this.modalOpen = true;
688
739
  const size = this.shape.dialog;
740
+ const commandContext = this.options.commandContext;
741
+ const session = new SearchSession({
742
+ catalog: this.options.catalog,
743
+ context: () => ({
744
+ projectId: commandContext.ctx.current.projectId ?? null,
745
+ projectName: commandContext.ctx.current.projectName,
746
+ }),
747
+ transport: (query, params, signal) => commandContext.api.searchChats(commandContext.token, params, signal),
748
+ scope: this.searchScope,
749
+ debounceMs: this.options.searchDebounceMs,
750
+ now: this.options.clock,
751
+ });
752
+ this.activeSearch = session;
753
+ const dialog = new SearchDialog({ title: session.title.peek(), width: size.width, height: size.height });
689
754
  const query = signal('');
690
- const rows = signal([]);
691
- const hint = signal('↑↓ выбор · Enter открыть · Esc назад');
692
- const dialog = new Dialog({ title: ' Глобальный поиск ', width: size.width, height: size.height });
693
- const input = at(new Input({ value: query, placeholder: 'Имя проекта или чата…' }), 1, 1, size.width - 2, 1);
694
- const list = at(new ListView({
695
- items: rows,
696
- getText: (row) => `${row.name} · ${row.scopeName}`,
697
- onSelect: (_index, row) => { this.loop.endModal('open'); void this.openChat(row.chatId); },
698
- }), 1, 4, size.width - 2, size.height - 7);
699
- const hintView = at(new LiveText(() => hint()), 1, 2, size.width - 2, 1);
755
+ const input = at(new Input({ value: query, placeholder: 'Название или фраза…' }), 1, 1, size.width - 2, 1);
756
+ const hintView = at(new Text('↑↓ выбор · PgUp/PgDn · Enter · Ctrl+G · Esc'), 1, 2, size.width - 2, 1);
757
+ const rows = at(new SearchRows({
758
+ items: session.rows,
759
+ focused: session.focused,
760
+ onActivate: (row) => { this.loop.endModal('open'); void this.openChat(row.chatId); },
761
+ onPageEnd: () => { session.requestMore(); },
762
+ }), 1, 3, size.width - 2, Math.max(1, size.height - 6));
763
+ const footer = searchFooterText(session);
700
764
  dialog.add(input);
701
765
  dialog.add(hintView);
702
- dialog.add(list);
703
- // Живой поиск: каждая правка запроса перечитывает binding.runSearch (честный
704
- // SearchOutcome остаётся честным); bind живёт в scope Dialog'а и снимается с ним.
766
+ dialog.add(rows);
767
+ // Последняя строка содержимого Dialog'а: рамка съедает по строке сверху и снизу.
768
+ dialog.add(at(footer, 1, size.height - 3, size.width - 2, 1));
769
+ dialog.onNav = (key) => {
770
+ if (key === 'up')
771
+ rows.move(-1);
772
+ else if (key === 'down')
773
+ rows.move(1);
774
+ else if (key === 'pageup')
775
+ rows.pageUp();
776
+ else if (key === 'pagedown')
777
+ rows.pageDown();
778
+ else
779
+ rows.activate();
780
+ };
781
+ dialog.onToggleScope = () => { session.toggleScope(); };
782
+ // Живой поиск: каждая правка запроса заводит новый epoch сессии; заголовок dialog'а
783
+ // следует за охватом (Ctrl+G меняет его без пересоздания Dialog'а).
705
784
  dialog.onMount(() => {
706
- dialog.bind(() => {
707
- const q = query();
708
- this.catalogBinding.runSearch(q);
709
- const state = this.catalogBinding.search.peek();
710
- rows.set(state?.rows ?? []);
711
- if (q.trim().length > 0)
712
- hint.set(`${state?.rows.length ?? 0} результатов · Enter открыть · Esc назад`);
713
- });
785
+ dialog.bind(() => { session.setQuery(query()); });
786
+ dialog.bind(() => { dialog.title.set(session.title()); });
714
787
  });
715
788
  this.window.add(dialog);
716
789
  try {
@@ -719,6 +792,9 @@ export class JvApp {
719
792
  finally {
720
793
  this.window.remove(dialog);
721
794
  this.modalOpen = false;
795
+ this.searchScope = session.scope;
796
+ this.activeSearch = null;
797
+ session.dispose();
722
798
  }
723
799
  }
724
800
  openNavigator() {
@@ -808,7 +884,7 @@ export class JvApp {
808
884
  const lines = [
809
885
  'F10 / Alt+П, В, М — открыть меню',
810
886
  'Tab / Shift+Tab — следующая / предыдущая область',
811
- 'Ctrl+K — глобальный поиск · Ctrl+U — очередь',
887
+ 'Ctrl+K — поиск чатов · Ctrl+G — охват (текущий/все проекты) · Ctrl+U — очередь',
812
888
  'Ctrl+N — новый чат · Ctrl+T — сменить тему без потери состояния',
813
889
  'Alt+1…3 — навигатор / разговор / контекст',
814
890
  'Enter в композере — отправить; во время хода — в очередь (одна клавиша:',
@@ -3,9 +3,12 @@
3
3
  // Ничего из наших типов не переписывает: строки собираются ровно теми же getters,
4
4
  // которые читает текущий экран (разбор jsvision-prototype README, «Стыковка с реальным
5
5
  // швом»): scopeKeys + project + projectChatCount; chatsOf/filterScope + chat(id);
6
- // recentView(records, serverUrl, userId) поверх RecentSource.forProfile(); searchChats
7
- // с честным SearchOutcome.complete. Имена и время — из CatalogChat.updatedAt;
8
- // sessionCount DTO — заглушка до загрузки scope, а не подмена projectChatCount.
6
+ // recentView(records, serverUrl, userId) поверх RecentSource.forProfile(). Имена и время —
7
+ // из CatalogChat.updatedAt; sessionCount DTO — заглушка до загрузки scope, а не подмена
8
+ // projectChatCount.
9
+ //
10
+ // Поиск сюда не входит: удалённый запрос с epoch/abort и локальный title-fallback живут
11
+ // в search.ts (SearchSession) — адаптер остаётся срезом каталога, без сети.
9
12
  //
10
13
  // Порядок строк — порядок стора (compareRows в CatalogStore), адаптер его не пересортировывает.
11
14
  // Обновление: subscribe стора → перечитать сигналы; повторный subscribe не плодит
@@ -37,7 +40,6 @@ export function bindCatalog(options) {
37
40
  const scopes = signal([]);
38
41
  const chats = signal([]);
39
42
  const recentSignal = signal([]);
40
- const search = signal(null);
41
43
  let selected = PERSONAL_SCOPE_KEY;
42
44
  let filter = '';
43
45
  let subscribed = null;
@@ -106,7 +108,6 @@ export function bindCatalog(options) {
106
108
  scopes,
107
109
  chats,
108
110
  recent: recentSignal,
109
- search,
110
111
  selectedScope: () => selected,
111
112
  // Смена scope — граница перечитывания: сигналы всегда текущего selected; поздний
112
113
  // сигнал стора перечитывает тот же selected, а не прежний scope.
@@ -124,22 +125,6 @@ export function bindCatalog(options) {
124
125
  return;
125
126
  subscribed = catalog.subscribe(publish);
126
127
  },
127
- runSearch: (query) => {
128
- const outcome = catalog.searchChats(query);
129
- const rows = [];
130
- for (const id of outcome.chatIds) {
131
- const chat = catalog.chat(id);
132
- if (!chat)
133
- continue;
134
- const scopeName = chat.projectId ? catalog.project(chat.projectId)?.name ?? chat.projectId : PERSONAL_NAME;
135
- const row = chatRow(id, () => ''); // timeText поисковой строке не нужен — поле остаётся пустым.
136
- if (row)
137
- rows.push({ chatId: id, name: row.name, scopeName });
138
- }
139
- if (!disposed)
140
- search.set({ query, outcome, rows });
141
- return outcome;
142
- },
143
128
  dispose: () => {
144
129
  disposed = true;
145
130
  if (subscribed === null)
@@ -11,6 +11,8 @@ import { Commands, createKeymap, item, menuBar, separator, statusItem, subMenu }
11
11
  export const JvCommands = {
12
12
  newChat: 'jv.new',
13
13
  search: 'jv.search',
14
+ /** Ctrl+G — охват поиска: текущий контекст ↔ все проекты; запоминается до следующего Ctrl+K. */
15
+ searchScope: 'jv.search.scope',
14
16
  queue: 'jv.queue',
15
17
  stop: 'jv.stop',
16
18
  navigator: 'jv.navigator',
@@ -54,6 +56,7 @@ export function jvKeymap() {
54
56
  return createKeymap({
55
57
  'ctrl+n': JvCommands.newChat,
56
58
  'ctrl+k': JvCommands.search,
59
+ 'ctrl+g': JvCommands.searchScope,
57
60
  'ctrl+u': JvCommands.queue,
58
61
  'ctrl+t': JvCommands.theme,
59
62
  'ctrl+f': JvCommands.filter,
@@ -0,0 +1,606 @@
1
+ // Поиск по чатам экрана B (CS-6, перенос на JSVision): состояние выдачи, удалённый запрос
2
+ // с epoch/abort и собственный список строк с подсветкой совпадения.
3
+ //
4
+ // Почему состояние и запрос живут здесь, а не в адаптере каталога: адаптер — read-only срез
5
+ // CatalogSource, а поиск ходит в REST с JWT и держит отмену в полёте. Транспорт передан швом
6
+ // (SearchSessionOptions.transport), поэтому сессия не знает ни ApiClient, ни токена — экран
7
+ // передаёт их сам, а тест подставляет очередь ответов.
8
+ //
9
+ // Мгновенный title-fallback из загруженного каталога — первый кадр выдачи: сеть ещё ничего
10
+ // не ответила, и футер честно говорит «по названиям». Удалённый ответ заменяет fallback,
11
+ // только если его epoch ещё свежий; снятие любой из двух защит (epoch и abort) делает выдачу
12
+ // гонкой поздних ответов.
13
+ //
14
+ // Список строк — свой View, а не ListView: ListView рисует getText одной строкой без стилей,
15
+ // а подчёркивание обязано лежать РОВНО на сегменте совпадения. Навигация (↑/↓/PgUp/PgDn)
16
+ // и активация Enter приходят из Dialog'а: фокус остаётся в поле ввода, чтобы набор не рвался.
17
+ import { Attr, Text, View, signal, stringWidth } from '@jsvision/ui';
18
+ import { ApiError, InvalidResponseError } from "../../api/client.js";
19
+ import { relTimeText } from "./catalog-adapter.js";
20
+ const PERSONAL_NAME = 'Личное';
21
+ /** Столько строк просит одна страница выдачи (та же величина, что на вебе). */
22
+ const SEARCH_LIMIT = 20;
23
+ /** Пауза между последней правкой запроса и удалённым запросом. */
24
+ export const SEARCH_DEBOUNCE_MS = 250;
25
+ /** Диапазон совпадения запроса в названии (регистронезависимо); null — не совпало. */
26
+ export function matchRange(name, query) {
27
+ const needle = query.trim().toLowerCase();
28
+ if (needle.length === 0)
29
+ return null;
30
+ const at = name.toLowerCase().indexOf(needle);
31
+ return at < 0 ? null : { start: at, end: at + needle.length };
32
+ }
33
+ /**
34
+ * Части серверного фрагмента в сегменты кадра: разметки нет по построению — только текст и
35
+ * флаг совпадения. Пробельные символы нормализуются в пробел (кадр строковый), соседние
36
+ * части одного флага склеиваются, края обрезаются.
37
+ */
38
+ export function snippetSegments(parts) {
39
+ const merged = [];
40
+ for (const part of parts) {
41
+ const text = String(part.text ?? '').replace(/\s+/g, ' ');
42
+ if (text.length === 0)
43
+ continue;
44
+ const previous = merged[merged.length - 1];
45
+ if (previous !== undefined && previous.match === (part.match === true))
46
+ previous.text += text;
47
+ else
48
+ merged.push({ text, match: part.match === true });
49
+ }
50
+ if (merged.length === 0)
51
+ return merged;
52
+ merged[0].text = merged[0].text.replace(/^ +/, '');
53
+ merged[merged.length - 1].text = merged[merged.length - 1].text.replace(/ +$/, '');
54
+ return merged.filter((segment) => segment.text.length > 0);
55
+ }
56
+ /** Текст отказа: выдача остаётся title-fallback, поэтому отказ не называется потерей. */
57
+ export function searchFailureText(err) {
58
+ if (err instanceof ApiError) {
59
+ if (err instanceof InvalidResponseError)
60
+ return 'Некорректный ответ поиска — показаны совпадения по названиям.';
61
+ if (err.status === 429)
62
+ return 'Слишком часто — показаны совпадения по названиям.';
63
+ if (err.status === 503)
64
+ return 'Поиск временно недоступен — показаны совпадения по названиям.';
65
+ if (err.status === 0)
66
+ return 'Нет связи — показаны совпадения по названиям.';
67
+ return err.message;
68
+ }
69
+ return err instanceof Error ? err.message : 'Поиск недоступен — показаны совпадения по названиям.';
70
+ }
71
+ /** Русское склонение счётчика строк выдачи (1 чат, 2 чата, 5 чатов). */
72
+ function pluralChats(count) {
73
+ const mod10 = count % 10;
74
+ const mod100 = count % 100;
75
+ const word = mod10 === 1 && mod100 !== 11
76
+ ? 'чат'
77
+ : mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)
78
+ ? 'чата'
79
+ : 'чатов';
80
+ return `${count} ${word}`;
81
+ }
82
+ function clampIndex(value, range) {
83
+ if (range <= 0)
84
+ return 0;
85
+ return Math.max(0, Math.min(range - 1, value));
86
+ }
87
+ /**
88
+ * Состояние поиска одного открытого диалога. Сигналы — то, что читает UI; сеть и epoch —
89
+ * внутри. Идемпотентный dispose: после него поздние ответы не трогают сигналы.
90
+ */
91
+ export class SearchSession {
92
+ rows;
93
+ focused;
94
+ footer;
95
+ title;
96
+ catalog;
97
+ context;
98
+ transport;
99
+ debounceMs;
100
+ now;
101
+ query = '';
102
+ scopeMode;
103
+ epoch = 0;
104
+ abort = null;
105
+ timer = null;
106
+ cursor = null;
107
+ complete = true;
108
+ contentSearched = false;
109
+ loading = false;
110
+ notice = null;
111
+ usedFallback = false;
112
+ scopesLoaded = 0;
113
+ scopesTotal = 0;
114
+ rowsState = [];
115
+ disposed = false;
116
+ constructor(options) {
117
+ this.catalog = options.catalog;
118
+ this.context = options.context;
119
+ this.transport = options.transport;
120
+ this.debounceMs = options.debounceMs ?? SEARCH_DEBOUNCE_MS;
121
+ this.now = options.now ?? (() => new Date());
122
+ this.scopeMode = options.scope ?? 'current';
123
+ this.rows = signal([]);
124
+ this.focused = signal(0);
125
+ this.footer = signal(this.footerText());
126
+ this.title = signal(this.titleText());
127
+ }
128
+ /** Текущий охват: его сохраняет экран после закрытия диалога. */
129
+ get scope() {
130
+ return this.scopeMode;
131
+ }
132
+ /** Новый запрос: новый epoch, отмена прежнего и пауза до удалённого вызова. */
133
+ setQuery(query) {
134
+ if (query === this.query)
135
+ return;
136
+ this.query = query;
137
+ this.beginSearch();
138
+ }
139
+ /** Ctrl+G: охват текущий ↔ все проекты; открытая выдача перезапрашивается. */
140
+ toggleScope() {
141
+ this.scopeMode = this.scopeMode === 'current' ? 'global' : 'current';
142
+ this.beginSearch();
143
+ }
144
+ /** PgDn на последней загруженной строке и наличии cursor — догрузка следующей страницы. */
145
+ requestMore() {
146
+ if (this.disposed || this.usedFallback || this.loading || this.cursor === null)
147
+ return;
148
+ if (this.focused.peek() >= this.rowsState.length - 1)
149
+ void this.runRemote(this.epoch, this.cursor, true);
150
+ }
151
+ dispose() {
152
+ if (this.disposed)
153
+ return;
154
+ this.disposed = true;
155
+ this.cancelRequest();
156
+ }
157
+ beginSearch() {
158
+ this.epoch += 1;
159
+ this.cancelRequest();
160
+ this.cursor = null;
161
+ this.complete = true;
162
+ this.contentSearched = false;
163
+ this.loading = false;
164
+ this.notice = null;
165
+ this.applyFallback();
166
+ this.publish();
167
+ const query = this.query.trim();
168
+ if (query.length === 0)
169
+ return;
170
+ const epoch = this.epoch;
171
+ this.timer = setTimeout(() => {
172
+ this.timer = null;
173
+ void this.runRemote(epoch, null, false);
174
+ }, this.debounceMs);
175
+ // CLI живёт без таймеров: отложенный запрос не должен держать процесс.
176
+ this.timer.unref?.();
177
+ }
178
+ /** Мгновенный ответ без сети: совпадения по названию и проекту из загруженного каталога. */
179
+ applyFallback() {
180
+ const query = this.query.trim();
181
+ this.usedFallback = true;
182
+ if (query.length === 0) {
183
+ this.rowsState = [];
184
+ this.scopesLoaded = 0;
185
+ this.scopesTotal = 0;
186
+ return;
187
+ }
188
+ const outcome = this.catalog.searchChats(query);
189
+ const currentProject = this.context().projectId;
190
+ const ids = this.scopeMode === 'current'
191
+ ? outcome.chatIds.filter((id) => (this.catalog.chat(id)?.projectId ?? null) === currentProject)
192
+ : outcome.chatIds;
193
+ this.rowsState = ids.map((id) => this.rowFromCatalog(id, query));
194
+ this.complete = outcome.complete;
195
+ this.scopesLoaded = outcome.scopesLoaded;
196
+ this.scopesTotal = outcome.scopesTotal;
197
+ }
198
+ rowFromCatalog(chatId, query) {
199
+ const chat = this.catalog.chat(chatId);
200
+ return {
201
+ chatId,
202
+ name: chat?.name ?? 'Без названия',
203
+ scopeName: chat?.projectId
204
+ ? this.catalog.project(chat.projectId)?.name ?? chat.projectId
205
+ : PERSONAL_NAME,
206
+ dateText: relTimeText(chat?.updatedAt ?? null, this.now()),
207
+ nameMatch: matchRange(chat?.name ?? '', query),
208
+ snippet: null,
209
+ };
210
+ }
211
+ rowFromItem(item, query) {
212
+ const chat = item.chat;
213
+ if (chat === null || typeof chat.id !== 'string' || chat.id.length === 0)
214
+ return null;
215
+ const name = typeof chat.name === 'string' && chat.name.length > 0 ? chat.name : 'Без названия';
216
+ const match = item.match ?? null;
217
+ return {
218
+ chatId: chat.id,
219
+ name,
220
+ scopeName: typeof item.projectName === 'string' && item.projectName.length > 0
221
+ ? item.projectName
222
+ : chat.projectId
223
+ ? this.catalog.project(chat.projectId)?.name ?? chat.projectId
224
+ : PERSONAL_NAME,
225
+ dateText: relTimeText(typeof chat.updatedAt === 'string' ? chat.updatedAt : null, this.now()),
226
+ nameMatch: matchRange(name, query),
227
+ snippet: match === null || match.parts === undefined ? null : snippetSegments(match.parts),
228
+ };
229
+ }
230
+ /** Параметры запроса по охвату: проект, «Личное» (без projectId) или все проекты. */
231
+ params(query, cursor) {
232
+ if (this.scopeMode === 'global')
233
+ return { q: query, global: true, limit: SEARCH_LIMIT, cursor };
234
+ const projectId = this.context().projectId;
235
+ if (projectId === null)
236
+ return { q: query, limit: SEARCH_LIMIT, cursor };
237
+ return { q: query, projectId, limit: SEARCH_LIMIT, cursor };
238
+ }
239
+ /**
240
+ * Удалённый запрос. Ключ — epoch: ответ (и ошибка) применяется, только если epoch всё ещё
241
+ * текущий. Abort уходит в сеть, но поздний ответ, успевший прийти, тоже отбрасывается:
242
+ * снятие любой из двух защит делает выдачу гонкой.
243
+ */
244
+ async runRemote(epoch, cursor, append) {
245
+ if (this.disposed || epoch !== this.epoch)
246
+ return;
247
+ const query = this.query.trim();
248
+ if (query.length === 0)
249
+ return;
250
+ this.abortRequest();
251
+ const controller = new AbortController();
252
+ this.abort = controller;
253
+ this.loading = true;
254
+ this.notice = null;
255
+ this.publish();
256
+ try {
257
+ const response = await this.transport(query, this.params(query, cursor), controller.signal);
258
+ if (epoch !== this.epoch || this.disposed)
259
+ return; // поздний ответ свежую выдачу не трогает
260
+ this.applyResponse(response, append);
261
+ }
262
+ catch (err) {
263
+ if (epoch !== this.epoch || controller.signal.aborted || this.disposed)
264
+ return; // поздняя ошибка — тихо
265
+ this.loading = false;
266
+ this.notice = searchFailureText(err);
267
+ this.publish();
268
+ }
269
+ finally {
270
+ if (this.abort === controller)
271
+ this.abort = null;
272
+ }
273
+ }
274
+ applyResponse(response, append) {
275
+ const query = this.query.trim();
276
+ const incoming = response.items
277
+ .map((item) => this.rowFromItem(item, query))
278
+ .filter((row) => row !== null);
279
+ if (append) {
280
+ const before = this.rowsState.length;
281
+ const known = new Set(this.rowsState.map((row) => row.chatId));
282
+ this.rowsState = [...this.rowsState, ...incoming.filter((row) => !known.has(row.chatId))];
283
+ // Догрузка пришла с PgDn на последней строке: выбор переходит на первую новую, иначе
284
+ // она осталась бы за нижним краем окна, а Enter открывал бы прежнюю строку.
285
+ if (before > 0 && this.focused.peek() >= before - 1 && this.rowsState.length > before) {
286
+ this.focused.set(before);
287
+ }
288
+ }
289
+ else {
290
+ this.rowsState = incoming;
291
+ }
292
+ this.cursor = typeof response.nextCursor === 'string' && response.nextCursor.length > 0 ? response.nextCursor : null;
293
+ this.complete = response.complete === true;
294
+ this.contentSearched = response.contentSearched === true;
295
+ this.loading = false;
296
+ this.notice = null;
297
+ this.usedFallback = false;
298
+ this.publish();
299
+ }
300
+ abortRequest() {
301
+ if (this.abort !== null) {
302
+ this.abort.abort();
303
+ this.abort = null;
304
+ }
305
+ }
306
+ cancelRequest() {
307
+ this.abortRequest();
308
+ if (this.timer !== null) {
309
+ clearTimeout(this.timer);
310
+ this.timer = null;
311
+ }
312
+ }
313
+ publish() {
314
+ if (this.disposed)
315
+ return;
316
+ this.rows.set([...this.rowsState]);
317
+ this.focused.set(clampIndex(this.focused.peek(), this.rowsState.length));
318
+ this.footer.set(this.footerText());
319
+ this.title.set(this.titleText());
320
+ }
321
+ titleText() {
322
+ const scopeTitle = this.scopeMode === 'global'
323
+ ? 'все проекты'
324
+ : this.context().projectId === null
325
+ ? PERSONAL_NAME
326
+ : this.context().projectName !== ''
327
+ ? this.context().projectName
328
+ : PERSONAL_NAME;
329
+ return `Поиск чатов · ${scopeTitle}`;
330
+ }
331
+ /** Футер: счётчик, честная неполнота и отказ — без «больше нет» и без обещаний content-поиска. */
332
+ footerText() {
333
+ if (this.notice !== null)
334
+ return `! ${this.notice}`;
335
+ if (this.loading)
336
+ return 'Ищу по названиям и сообщениям…';
337
+ if (this.rowsState.length === 0) {
338
+ if (this.query.trim().length === 0)
339
+ return 'Введите название или фразу — поиск по названиям и сообщениям.';
340
+ return `По «${this.query.trim()}» ничего не найдено. Ctrl+G расширяет охват.`;
341
+ }
342
+ if (!this.complete) {
343
+ if (this.usedFallback && this.scopeMode === 'global') {
344
+ return `проверено ${this.scopesLoaded} из ${this.scopesTotal} проектов · результаты неполные`;
345
+ }
346
+ return `${pluralChats(this.rowsState.length)} · результаты неполные`;
347
+ }
348
+ if (!this.contentSearched)
349
+ return `${pluralChats(this.rowsState.length)} · по названиям`;
350
+ return `${pluralChats(this.rowsState.length)} · названия и сообщения`;
351
+ }
352
+ }
353
+ /** Обрезка сегментов по ширине кадра без разрыва широких символов. */
354
+ function fitRuns(runs, maxWidth) {
355
+ const out = [];
356
+ let used = 0;
357
+ for (const run of runs) {
358
+ if (used >= maxWidth)
359
+ break;
360
+ let text = '';
361
+ for (const ch of run.text) {
362
+ const width = stringWidth(ch);
363
+ if (used + width > maxWidth)
364
+ break;
365
+ text += ch;
366
+ used += width;
367
+ }
368
+ if (text.length > 0)
369
+ out.push({ ...run, text });
370
+ if (used >= maxWidth)
371
+ break;
372
+ }
373
+ return out;
374
+ }
375
+ /**
376
+ * Список выдачи: строка чата занимает первую линию (имя слева, проект и дата справа),
377
+ * фрагмент найденного сообщения — вторую линию под ней. Мета не прячется за фрагментом:
378
+ * в глобальной выдаче по ней различаются одноимённые проекты. Подчёркивание — только на
379
+ * совпавшем сегменте. Фокус остаётся в поле ввода (focusable=false, grabsFocus=false):
380
+ * клавиши навигации приходят из Dialog'а, и набор запроса не прерывается. ↑/↓, PgUp/PgDn,
381
+ * Enter, мышь.
382
+ */
383
+ export class SearchRows extends View {
384
+ items;
385
+ focusedSignal;
386
+ selectedSignal;
387
+ onActivate;
388
+ onPageEnd;
389
+ top = 0;
390
+ constructor(opts) {
391
+ super();
392
+ this.items = opts.items;
393
+ this.focusedSignal = opts.focused;
394
+ this.selectedSignal = signal(-1);
395
+ this.onActivate = opts.onActivate;
396
+ this.onPageEnd = opts.onPageEnd;
397
+ this.focusable = false;
398
+ this.grabsFocus = false;
399
+ // onMount — регистрация хука, не переопределяемый метод: bind живёт в scope вида.
400
+ this.onMount(() => {
401
+ this.bind(() => {
402
+ this.items();
403
+ this.focusedSignal();
404
+ this.selectedSignal();
405
+ });
406
+ });
407
+ }
408
+ /** Переместить выбор на delta строк. */
409
+ move(delta) {
410
+ const range = this.items().length;
411
+ if (range === 0)
412
+ return;
413
+ this.focusedSignal.set(clampIndex(this.focusedSignal() + delta, range));
414
+ this.invalidate();
415
+ }
416
+ pageUp() {
417
+ this.move(-this.pageSize());
418
+ }
419
+ /** PgDn: страница вперёд; на последней загруженной строке — догрузка по cursor. */
420
+ pageDown() {
421
+ const range = this.items().length;
422
+ if (range === 0)
423
+ return;
424
+ const current = clampIndex(this.focusedSignal(), range);
425
+ if (current >= range - 1) {
426
+ this.onPageEnd();
427
+ return;
428
+ }
429
+ this.focusedSignal.set(clampIndex(current + this.pageSize(), range));
430
+ this.invalidate();
431
+ }
432
+ /** Enter: открыть выбранную строку. */
433
+ activate() {
434
+ const rows = this.items();
435
+ const row = rows[clampIndex(this.focusedSignal(), rows.length)];
436
+ if (row !== undefined)
437
+ this.onActivate(row);
438
+ }
439
+ onEvent(ev) {
440
+ const inner = ev.event;
441
+ if (inner.type === 'wheel') {
442
+ this.move(inner.dir === 'up' ? -1 : 1);
443
+ ev.handled = true;
444
+ return;
445
+ }
446
+ if (inner.type === 'mouse' && inner.kind === 'down' && ev.local !== undefined) {
447
+ const index = this.itemAtLine(this.top + ev.local.y);
448
+ if (index !== null) {
449
+ this.focusedSignal.set(index);
450
+ this.selectedSignal.set(index);
451
+ if (ev.clickCount === 2)
452
+ this.activate();
453
+ ev.handled = true;
454
+ }
455
+ }
456
+ }
457
+ draw(ctx) {
458
+ const rows = this.items();
459
+ const range = rows.length;
460
+ const height = ctx.size.height;
461
+ const width = ctx.size.width;
462
+ const normal = ctx.color('listNormal');
463
+ if (range === 0 || height <= 0 || width <= 0) {
464
+ ctx.fill(' ', normal);
465
+ return;
466
+ }
467
+ const lines = this.buildLines(rows);
468
+ const focused = clampIndex(this.focusedSignal(), range);
469
+ // Линии выбранного чата: имя видно всегда, фрагмент — если хватает высоты окна.
470
+ let focusStart = -1;
471
+ let focusEnd = -1;
472
+ for (let at = 0; at < lines.length; at += 1) {
473
+ if (lines[at].index !== focused)
474
+ continue;
475
+ if (focusStart < 0)
476
+ focusStart = at;
477
+ focusEnd = at;
478
+ }
479
+ if (focusStart < this.top)
480
+ this.top = focusStart;
481
+ else if (focusEnd >= this.top + height)
482
+ this.top = Math.min(focusStart, focusEnd - height + 1);
483
+ this.top = Math.max(0, Math.min(this.top, Math.max(0, lines.length - height)));
484
+ const selected = this.selectedSignal();
485
+ for (let offset = 0; offset < height; offset += 1) {
486
+ const at = this.top + offset;
487
+ const line = at < lines.length ? lines[at] : null;
488
+ const role = line !== null && (line.index === focused || line.index === selected) ? 'listSelected' : 'listNormal';
489
+ const base = ctx.color(role);
490
+ ctx.fillRect(0, offset, width, 1, ' ', base);
491
+ if (line === null)
492
+ continue;
493
+ const isFocused = line.index === focused;
494
+ const textX = isFocused ? 2 : 1;
495
+ if (isFocused && !line.snippet)
496
+ ctx.text(0, offset, '>', base);
497
+ if (line.snippet)
498
+ this.drawSnippet(ctx, line.row, textX, offset, width, base);
499
+ else
500
+ this.drawName(ctx, line.row, textX, offset, width, base);
501
+ }
502
+ }
503
+ /** Строки кадра: у чата с фрагментом их две — имя с метой и сам фрагмент. */
504
+ buildLines(rows) {
505
+ const lines = [];
506
+ rows.forEach((row, index) => {
507
+ lines.push({ row, index, snippet: false });
508
+ if (hasSnippet(row))
509
+ lines.push({ row, index, snippet: true });
510
+ });
511
+ return lines;
512
+ }
513
+ /** Номер чата по линии кадра: фрагмент кликается как та же строка. */
514
+ itemAtLine(line) {
515
+ if (line < 0)
516
+ return null;
517
+ const rows = this.items();
518
+ let at = 0;
519
+ for (let index = 0; index < rows.length; index += 1) {
520
+ at += hasSnippet(rows[index]) ? 2 : 1;
521
+ if (line < at)
522
+ return index;
523
+ }
524
+ return null;
525
+ }
526
+ /** Сколько строк целиком помещается в окно: фрагмент занимает отдельную линию. */
527
+ pageSize() {
528
+ const height = this.bounds.height || 1;
529
+ let used = 0;
530
+ let count = 0;
531
+ for (const row of this.items()) {
532
+ const span = hasSnippet(row) ? 2 : 1;
533
+ if (used + span > height)
534
+ break;
535
+ used += span;
536
+ count += 1;
537
+ }
538
+ return Math.max(1, count);
539
+ }
540
+ /** Первая линия чата: имя слева, проект и дата — приглушённо у правого края. */
541
+ drawName(ctx, row, textX, line, width, base) {
542
+ const avail = width - textX;
543
+ if (avail <= 0)
544
+ return;
545
+ const meta = this.metaRuns(row, avail);
546
+ const metaWidth = meta.reduce((sum, run) => sum + stringWidth(run.text), 0);
547
+ // Место под мету резервируется до обрезки имени: проект и дату не прячет длинное имя.
548
+ const bodyMax = Math.max(0, avail - (metaWidth > 0 ? metaWidth + 1 : 0));
549
+ let x = textX;
550
+ for (const run of fitRuns(this.nameRuns(row), bodyMax)) {
551
+ ctx.text(x, line, run.text, this.runStyle(ctx, base, run));
552
+ x += stringWidth(run.text);
553
+ }
554
+ let metaX = textX + Math.max(0, avail - metaWidth);
555
+ for (const run of meta) {
556
+ ctx.text(metaX, line, run.text, this.runStyle(ctx, base, run));
557
+ metaX += stringWidth(run.text);
558
+ }
559
+ }
560
+ /** Вторая линия чата: фрагмент найденного сообщения, совпадение — подчёркнуто. */
561
+ drawSnippet(ctx, row, textX, line, width, base) {
562
+ let x = textX;
563
+ for (const run of fitRuns(this.snippetRuns(row), width - textX)) {
564
+ ctx.text(x, line, run.text, this.runStyle(ctx, base, run));
565
+ x += stringWidth(run.text);
566
+ }
567
+ }
568
+ runStyle(ctx, base, run) {
569
+ if (run.match)
570
+ return { ...base, attrs: (base.attrs ?? 0) | Attr.underline };
571
+ return run.muted === true ? ctx.color('listDivider') : base;
572
+ }
573
+ /** Имя с подсветкой совпадения запроса. */
574
+ nameRuns(row) {
575
+ const runs = [];
576
+ const range = row.nameMatch;
577
+ if (range === null) {
578
+ runs.push({ text: row.name, match: false });
579
+ }
580
+ else {
581
+ if (range.start > 0)
582
+ runs.push({ text: row.name.slice(0, range.start), match: false });
583
+ runs.push({ text: row.name.slice(range.start, range.end), match: true });
584
+ if (range.end < row.name.length)
585
+ runs.push({ text: row.name.slice(range.end), match: false });
586
+ }
587
+ return runs;
588
+ }
589
+ /** Фрагмент сообщения (null не встречается: вызывается только при наличии). */
590
+ snippetRuns(row) {
591
+ return (row.snippet ?? []).map((segment) => ({ text: segment.text, match: segment.match }));
592
+ }
593
+ /** Мета справа: проект и дата; на тесной ширине обрезается, но не исчезает целиком. */
594
+ metaRuns(row, maxWidth) {
595
+ const text = row.dateText.length > 0 ? `${row.scopeName} · ${row.dateText}` : row.scopeName;
596
+ return fitRuns([{ text, match: false, muted: true }], maxWidth);
597
+ }
598
+ }
599
+ /** Есть ли у строки фрагмент: у такого чата в кадре две линии. */
600
+ function hasSnippet(row) {
601
+ return row.snippet !== null && row.snippet.length > 0;
602
+ }
603
+ /** Живая строка футера: Text с getter'ом, чтобы перерисовываться на сигналах сессии. */
604
+ export function searchFooterText(session) {
605
+ return new Text(() => session.footer());
606
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-home-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "AI Home CLI — текстовый клиент AI Home: вход, профиль и построчный REPL",
5
5
  "type": "module",
6
6
  "bin": {