@shliamb/dsh-telegram-bot 0.2.3 → 0.2.5
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 +5 -4
- package/README.ru.md +5 -4
- package/lib/index.js +109 -42
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -59,13 +59,13 @@ Adding a new bundle requires a Host restart. Chat sessions and bindings survive
|
|
|
59
59
|
The repository also contains a ready-to-install archive:
|
|
60
60
|
|
|
61
61
|
```text
|
|
62
|
-
dist/shliamb-dsh-telegram-bot-0.2.
|
|
62
|
+
dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
63
63
|
```
|
|
64
64
|
|
|
65
65
|
If the `dsh` CLI is on your `PATH`, run this from the repository root:
|
|
66
66
|
|
|
67
67
|
```bash
|
|
68
|
-
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.
|
|
68
|
+
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
69
69
|
dsh web
|
|
70
70
|
```
|
|
71
71
|
|
|
@@ -73,7 +73,7 @@ If you run Harness from a source checkout, use `pnpm dsh` from that checkout and
|
|
|
73
73
|
|
|
74
74
|
```bash
|
|
75
75
|
cd /path/to/deepseek-harness
|
|
76
|
-
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.
|
|
76
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
77
77
|
pnpm dsh web
|
|
78
78
|
```
|
|
79
79
|
|
|
@@ -179,7 +179,8 @@ Final answers are sent as separate rich messages. Long text is split into parts
|
|
|
179
179
|
After you choose a workspace:
|
|
180
180
|
|
|
181
181
|
- if it has one session, that session is selected automatically;
|
|
182
|
-
- if it has several, an inline picker
|
|
182
|
+
- if it has several, an inline picker appears: `✅` is the current session, `🟢` is running and `⚪` is idle;
|
|
183
|
+
- empty draft sessions are hidden and reused by **New session**, so pressing it twice does not create duplicates;
|
|
183
184
|
- if it has none, a session is created when you send the first message.
|
|
184
185
|
|
|
185
186
|
Text sent before a session is selected is not lost: it waits in `pendingPrompt` and is submitted after the selection.
|
package/README.ru.md
CHANGED
|
@@ -59,13 +59,13 @@ pnpm dsh web
|
|
|
59
59
|
В репозитории также лежит готовый к установке архив:
|
|
60
60
|
|
|
61
61
|
```text
|
|
62
|
-
dist/shliamb-dsh-telegram-bot-0.2.
|
|
62
|
+
dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
63
63
|
```
|
|
64
64
|
|
|
65
65
|
Если команда `dsh` доступна в `PATH`, выполните из корня репозитория:
|
|
66
66
|
|
|
67
67
|
```bash
|
|
68
|
-
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.
|
|
68
|
+
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
69
69
|
dsh web
|
|
70
70
|
```
|
|
71
71
|
|
|
@@ -73,7 +73,7 @@ dsh web
|
|
|
73
73
|
|
|
74
74
|
```bash
|
|
75
75
|
cd /path/to/deepseek-harness
|
|
76
|
-
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.
|
|
76
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.5.tgz
|
|
77
77
|
pnpm dsh web
|
|
78
78
|
```
|
|
79
79
|
|
|
@@ -179,7 +179,8 @@ ID админа хранится в конфиге плагина. Если `all
|
|
|
179
179
|
После выбора пространства:
|
|
180
180
|
|
|
181
181
|
- если сессия одна — она выбирается автоматически;
|
|
182
|
-
- если сессий несколько — появляется inline
|
|
182
|
+
- если сессий несколько — появляется inline-список: `✅` — текущая, `🟢` — работает, `⚪` — ожидает;
|
|
183
|
+
- пустые черновики сессий скрыты и переиспользуются кнопкой «Новая сессия», поэтому повторное нажатие не плодит дубли;
|
|
183
184
|
- если сессий нет — новая создаётся при первом сообщении.
|
|
184
185
|
|
|
185
186
|
Текст, отправленный до выбора сессии, не теряется: он ждёт в `pendingPrompt` и уходит после выбора.
|
package/lib/index.js
CHANGED
|
@@ -33,6 +33,12 @@ const STRINGS = {
|
|
|
33
33
|
choose: 'Выбери рабочее пространство:',
|
|
34
34
|
active: 'Активное',
|
|
35
35
|
none: 'Пространств пока нет. Создай его в DSH Web.',
|
|
36
|
+
workspace: 'Пространство',
|
|
37
|
+
tool: 'Инструмент',
|
|
38
|
+
workspacesCount: 'Рабочих пространств',
|
|
39
|
+
tokens: 'токенов',
|
|
40
|
+
cmdStart: 'Меню и баланс',
|
|
41
|
+
cmdAdmin: 'Админ-меню',
|
|
36
42
|
write: 'Потом просто напиши текст.',
|
|
37
43
|
refresh: '🔄 Обновить',
|
|
38
44
|
notFound: 'Пространство не найдено',
|
|
@@ -51,7 +57,8 @@ const STRINGS = {
|
|
|
51
57
|
workspaceMissing: 'Пространство не найдено. Выбери заново.',
|
|
52
58
|
noWorkspace: 'Сначала выбери рабочее пространство: /menu',
|
|
53
59
|
selectSession: 'Выбери сессию:',
|
|
54
|
-
noSessions: 'В этом пространстве пока нет сессий.
|
|
60
|
+
noSessions: 'В этом пространстве пока нет сессий. Нажми «Новая сессия» или просто напиши текст.',
|
|
61
|
+
sessionLegend: '✅ — текущая, 🟢 — работает, ⚪ — ожидает',
|
|
55
62
|
sessions: '🔄 Сессии',
|
|
56
63
|
backToWorkspaces: '◀️ Пространства',
|
|
57
64
|
newSession: '➕ Новая сессия',
|
|
@@ -140,6 +147,12 @@ const STRINGS = {
|
|
|
140
147
|
choose: 'Choose a workspace:',
|
|
141
148
|
active: 'Active',
|
|
142
149
|
none: 'No workspaces yet. Create one in DSH Web.',
|
|
150
|
+
workspace: 'Workspace',
|
|
151
|
+
tool: 'Tool',
|
|
152
|
+
workspacesCount: 'Workspaces',
|
|
153
|
+
tokens: 'tokens',
|
|
154
|
+
cmdStart: 'Menu and balance',
|
|
155
|
+
cmdAdmin: 'Admin menu',
|
|
143
156
|
write: 'Then just send text.',
|
|
144
157
|
refresh: '🔄 Refresh',
|
|
145
158
|
notFound: 'Workspace not found',
|
|
@@ -158,7 +171,8 @@ const STRINGS = {
|
|
|
158
171
|
workspaceMissing: 'Workspace not found. Choose it again.',
|
|
159
172
|
noWorkspace: 'Choose a workspace first: /menu',
|
|
160
173
|
selectSession: 'Choose a session:',
|
|
161
|
-
noSessions: 'No sessions in this workspace yet.
|
|
174
|
+
noSessions: 'No sessions in this workspace yet. Tap New session or just send text.',
|
|
175
|
+
sessionLegend: '✅ current, 🟢 running, ⚪ idle',
|
|
162
176
|
sessions: '🔄 Sessions',
|
|
163
177
|
backToWorkspaces: '◀️ Workspaces',
|
|
164
178
|
newSession: '➕ New session',
|
|
@@ -420,7 +434,7 @@ async function resolveBotToken(ctx, config, credentials, signal) {
|
|
|
420
434
|
function commandsFor(locale) {
|
|
421
435
|
return [{
|
|
422
436
|
command: 'start',
|
|
423
|
-
description: locale
|
|
437
|
+
description: t(locale, 'cmdStart'),
|
|
424
438
|
}];
|
|
425
439
|
}
|
|
426
440
|
function adminCommandsFor(locale) {
|
|
@@ -428,17 +442,23 @@ function adminCommandsFor(locale) {
|
|
|
428
442
|
...commandsFor(locale),
|
|
429
443
|
{
|
|
430
444
|
command: 'admin',
|
|
431
|
-
description: locale
|
|
445
|
+
description: t(locale, 'cmdAdmin'),
|
|
432
446
|
},
|
|
433
447
|
];
|
|
434
448
|
}
|
|
435
449
|
async function installCommands(bot, logger, adminUserId) {
|
|
436
450
|
try {
|
|
451
|
+
// Every non-ru interface falls back to English, including languages that
|
|
452
|
+
// have no dedicated list. Telegram uses the default list for those.
|
|
453
|
+
await bot.api.setMyCommands(commandsFor('en'));
|
|
437
454
|
await bot.api.setMyCommands(commandsFor('ru'), { language_code: 'ru' });
|
|
438
455
|
await bot.api.setMyCommands(commandsFor('en'), { language_code: 'en' });
|
|
439
456
|
if (adminUserId === undefined)
|
|
440
457
|
return;
|
|
441
458
|
// Only the admin sees /admin in the Telegram command list.
|
|
459
|
+
await bot.api.setMyCommands(adminCommandsFor('en'), {
|
|
460
|
+
scope: { type: 'chat', chat_id: adminUserId },
|
|
461
|
+
});
|
|
442
462
|
await bot.api.setMyCommands(adminCommandsFor('ru'), {
|
|
443
463
|
scope: { type: 'chat', chat_id: adminUserId },
|
|
444
464
|
language_code: 'ru',
|
|
@@ -473,7 +493,7 @@ async function getBalance(runtime, locale, force = false) {
|
|
|
473
493
|
}
|
|
474
494
|
try {
|
|
475
495
|
const result = await runtime.account.getBalance({
|
|
476
|
-
version: '@shliamb/dsh-telegram-bot/0.2.
|
|
496
|
+
version: '@shliamb/dsh-telegram-bot/0.2.4',
|
|
477
497
|
locale,
|
|
478
498
|
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
479
499
|
});
|
|
@@ -505,10 +525,9 @@ async function getBalance(runtime, locale, force = false) {
|
|
|
505
525
|
return cache.value === undefined ? {} : { display: cache.value, amount: cache.amount, currency: cache.currency };
|
|
506
526
|
}
|
|
507
527
|
}
|
|
508
|
-
async function
|
|
509
|
-
if (runtime.tokenMeter === undefined
|
|
528
|
+
async function getSessionContextLabel(runtime, sessionId) {
|
|
529
|
+
if (runtime.tokenMeter === undefined)
|
|
510
530
|
return undefined;
|
|
511
|
-
const sessionId = binding.activeSessionId;
|
|
512
531
|
const cached = runtime.contextCache.get(sessionId);
|
|
513
532
|
if (cached !== undefined && Date.now() - cached.at < 15_000) {
|
|
514
533
|
return cached.percent === undefined ? undefined : `${cached.percent}%`;
|
|
@@ -518,10 +537,14 @@ async function getContextLabel(runtime, binding) {
|
|
|
518
537
|
if (result.agent === undefined)
|
|
519
538
|
return undefined;
|
|
520
539
|
const pressure = runtime.tokenMeter.contextPressure(result.agent.session);
|
|
521
|
-
|
|
540
|
+
// `pressureTokens` is the last request's prompt size and cannot see a
|
|
541
|
+
// compaction. `projectedTokens` applies the surface delta since that
|
|
542
|
+
// sample, matching the Web context meter.
|
|
543
|
+
const used = pressure.projectedTokens ?? pressure.pressureTokens;
|
|
544
|
+
const percent = used !== undefined
|
|
522
545
|
&& pressure.contextWindow !== undefined
|
|
523
546
|
&& pressure.contextWindow > 0
|
|
524
|
-
? Math.round(100 *
|
|
547
|
+
? Math.round(100 * used / pressure.contextWindow)
|
|
525
548
|
: undefined;
|
|
526
549
|
runtime.contextCache.set(sessionId, { percent, at: Date.now() });
|
|
527
550
|
return percent === undefined ? undefined : `${percent}%`;
|
|
@@ -531,6 +554,11 @@ async function getContextLabel(runtime, binding) {
|
|
|
531
554
|
return undefined;
|
|
532
555
|
}
|
|
533
556
|
}
|
|
557
|
+
async function getContextLabel(runtime, binding) {
|
|
558
|
+
if (binding?.activeSessionId === undefined)
|
|
559
|
+
return undefined;
|
|
560
|
+
return getSessionContextLabel(runtime, binding.activeSessionId);
|
|
561
|
+
}
|
|
534
562
|
async function getMenuState(runtime, chatId, locale) {
|
|
535
563
|
const binding = runtime.store.get(chatId);
|
|
536
564
|
const [balance, context] = await Promise.all([
|
|
@@ -606,7 +634,7 @@ function compactResultText(locale, text) {
|
|
|
606
634
|
if (text.includes('could not be saved'))
|
|
607
635
|
return t(locale, 'compactPersistence');
|
|
608
636
|
const counts = /Compacted (\d+) history items \(~(\d+) tokens\)/.exec(text);
|
|
609
|
-
return counts === null ? text : `${t(locale, 'compactDone')} ${counts[1]} / ~${counts[2]} tokens`;
|
|
637
|
+
return counts === null ? text : `${t(locale, 'compactDone')} ${counts[1]} / ~${counts[2]} ${t(locale, 'tokens')}`;
|
|
610
638
|
}
|
|
611
639
|
async function runCompact(runtime, chatId, locale, sessionId) {
|
|
612
640
|
const result = await runtime.sessions.resolveAgent(sessionId);
|
|
@@ -629,7 +657,9 @@ async function runCompact(runtime, chatId, locale, sessionId) {
|
|
|
629
657
|
sessionId,
|
|
630
658
|
kind: execution.result.kind,
|
|
631
659
|
});
|
|
632
|
-
|
|
660
|
+
const summary = compactResultText(locale, execution.result.text);
|
|
661
|
+
const context = await getSessionContextLabel(runtime, sessionId);
|
|
662
|
+
return context === undefined ? summary : `${summary}\n${t(locale, 'context')}: ${context}`;
|
|
633
663
|
}
|
|
634
664
|
catch (error) {
|
|
635
665
|
runtime.logger.error('compact-failed', messageOf(error), {
|
|
@@ -653,7 +683,7 @@ async function statusText(runtime, chatId, locale) {
|
|
|
653
683
|
return [
|
|
654
684
|
t(locale, 'statusTitle'),
|
|
655
685
|
`${t(locale, 'balance')}: ${balance.display ?? '—'}`,
|
|
656
|
-
`${locale
|
|
686
|
+
`${t(locale, 'workspace')}: ${workspace?.title ?? t(locale, 'notSelected')}`,
|
|
657
687
|
`${t(locale, 'session')}: ${binding?.activeSessionId?.slice(0, 8) ?? t(locale, 'notSelectedSession')}`,
|
|
658
688
|
`${t(locale, 'agent')}: ${agentStatus === 'running' ? t(locale, 'running') : agentStatus === 'idle' ? t(locale, 'idle') : agentStatus}`,
|
|
659
689
|
`${t(locale, 'context')}: ${context ?? '—'}`,
|
|
@@ -744,13 +774,13 @@ function buildApprovalView(request, token, locale) {
|
|
|
744
774
|
const reason = request.reason === undefined ? '' : `<p>${escapeHtml(request.reason)}</p>`;
|
|
745
775
|
const html = [
|
|
746
776
|
`<h2>${escapeHtml(t(locale, 'approvalTitle'))}</h2>`,
|
|
747
|
-
`<p><b>${escapeHtml(locale
|
|
777
|
+
`<p><b>${escapeHtml(t(locale, 'tool'))}:</b> ${escapeHtml(request.toolName)}</p>`,
|
|
748
778
|
reason,
|
|
749
779
|
`<tg-button-row align="left"><tg-button type="callback_data" style="success" data="ap:${token}:a">${escapeHtml(t(locale, 'approvalAllow'))}</tg-button><tg-button type="callback_data" style="danger" data="ap:${token}:r">${escapeHtml(t(locale, 'approvalDeny'))}</tg-button></tg-button-row>`,
|
|
750
780
|
].join('\n');
|
|
751
781
|
const text = [
|
|
752
782
|
t(locale, 'approvalTitle'),
|
|
753
|
-
`${locale
|
|
783
|
+
`${t(locale, 'tool')}: ${request.toolName}`,
|
|
754
784
|
...(request.reason === undefined ? [] : [request.reason]),
|
|
755
785
|
].join('\n');
|
|
756
786
|
const keyboard = new InlineKeyboard()
|
|
@@ -941,18 +971,7 @@ async function askQuestion(runtime, chatId, sessionId, locale, question, questio
|
|
|
941
971
|
pending.messageId = messageId;
|
|
942
972
|
runtime.pendingQuestions.set(token, pending);
|
|
943
973
|
runtime.pendingQuestionChats.set(chatId, token);
|
|
944
|
-
|
|
945
|
-
await editProgress(runtime, sessionId, t(locale, 'questionWaiting'), false);
|
|
946
|
-
}
|
|
947
|
-
runtime.logger.info('question-shown', 'agent question sent to Telegram', {
|
|
948
|
-
chatId,
|
|
949
|
-
sessionId,
|
|
950
|
-
questionId: question.id,
|
|
951
|
-
index: questionIndex,
|
|
952
|
-
total: questionTotal,
|
|
953
|
-
multi: pending.multi,
|
|
954
|
-
});
|
|
955
|
-
return await new Promise(resolve => {
|
|
974
|
+
const answerPromise = new Promise(resolve => {
|
|
956
975
|
let settled = false;
|
|
957
976
|
let timer;
|
|
958
977
|
const finish = (answer, outcome) => {
|
|
@@ -980,7 +999,21 @@ async function askQuestion(runtime, chatId, sessionId, locale, question, questio
|
|
|
980
999
|
finishStep = finish;
|
|
981
1000
|
timer = setTimeout(() => finish(skip(), 'timeout'), Math.max(0, deadline - Date.now()));
|
|
982
1001
|
signal?.addEventListener('abort', () => finish(skip(), 'cancelled'), { once: true });
|
|
1002
|
+
if (isAborted())
|
|
1003
|
+
finish(skip(), 'cancelled');
|
|
983
1004
|
});
|
|
1005
|
+
if (runtime.progress.has(sessionId)) {
|
|
1006
|
+
void editProgress(runtime, sessionId, t(locale, 'questionWaiting'), false);
|
|
1007
|
+
}
|
|
1008
|
+
runtime.logger.info('question-shown', 'agent question sent to Telegram', {
|
|
1009
|
+
chatId,
|
|
1010
|
+
sessionId,
|
|
1011
|
+
questionId: question.id,
|
|
1012
|
+
index: questionIndex,
|
|
1013
|
+
total: questionTotal,
|
|
1014
|
+
multi: pending.multi,
|
|
1015
|
+
});
|
|
1016
|
+
return await answerPromise;
|
|
984
1017
|
}
|
|
985
1018
|
async function handleQuestion(runtime, request, next) {
|
|
986
1019
|
if (request.agent === undefined)
|
|
@@ -1077,7 +1110,7 @@ function buildWorkspaceView(workspaces, binding, locale) {
|
|
|
1077
1110
|
keyboard.text(t(locale, 'home'), 'menu:home');
|
|
1078
1111
|
const active = list.find(workspace => workspace.id === binding?.activeWorkspaceId);
|
|
1079
1112
|
const lines = [
|
|
1080
|
-
`${locale
|
|
1113
|
+
`${t(locale, 'workspacesCount')}: ${workspaces.length}`,
|
|
1081
1114
|
...(active === undefined ? [t(locale, 'choose')] : [`${t(locale, 'active')}: ${active.title}`]),
|
|
1082
1115
|
'',
|
|
1083
1116
|
t(locale, 'write'),
|
|
@@ -1109,7 +1142,7 @@ function buildMainMenu(workspaces, state, locale) {
|
|
|
1109
1142
|
: `<tg-button type="disabled" style="${style}">${escapeHtml(label)}</tg-button>`;
|
|
1110
1143
|
const html = [
|
|
1111
1144
|
`<h1>${escapeHtml(balance)}</h1>`,
|
|
1112
|
-
`<p><b>${escapeHtml(locale
|
|
1145
|
+
`<p><b>${escapeHtml(t(locale, 'workspace'))}:</b> ${escapeHtml(workspaceLabel)}</p>`,
|
|
1113
1146
|
`<p><b>${escapeHtml(t(locale, 'session'))}:</b> ${escapeHtml(sessionLabel)}</p>`,
|
|
1114
1147
|
`<p><b>${escapeHtml(t(locale, 'context'))}:</b> ${escapeHtml(context)}</p>`,
|
|
1115
1148
|
`<tg-button-row align="left">${button(t(locale, 'workspaces'), 'menu:workspaces', 'primary', true)}${button(t(locale, 'sessions'), 'menu:sessions', 'primary', hasWorkspace)}</tg-button-row>`,
|
|
@@ -1118,7 +1151,7 @@ function buildMainMenu(workspaces, state, locale) {
|
|
|
1118
1151
|
].join('\n');
|
|
1119
1152
|
const text = [
|
|
1120
1153
|
balance,
|
|
1121
|
-
`${locale
|
|
1154
|
+
`${t(locale, 'workspace')}: ${workspaceLabel}`,
|
|
1122
1155
|
`${t(locale, 'session')}: ${sessionLabel}`,
|
|
1123
1156
|
`${t(locale, 'context')}: ${context}`,
|
|
1124
1157
|
'',
|
|
@@ -1269,16 +1302,25 @@ async function listSessions(runtime, workspace) {
|
|
|
1269
1302
|
return fallback();
|
|
1270
1303
|
}
|
|
1271
1304
|
}
|
|
1272
|
-
function
|
|
1305
|
+
function visibleSessions(sessions) {
|
|
1306
|
+
// A blank Session is a draft, not a choice: "new session" is an action.
|
|
1307
|
+
return sessions.filter(session => !session.blank);
|
|
1308
|
+
}
|
|
1309
|
+
function buildSessionsView(workspace, sessions, locale, activeSessionId) {
|
|
1310
|
+
const visible = visibleSessions(sessions);
|
|
1273
1311
|
const keyboard = new InlineKeyboard();
|
|
1274
|
-
for (const session of
|
|
1312
|
+
for (const session of visible.slice(0, 8)) {
|
|
1275
1313
|
const mark = session.running ? '🟢' : '⚪';
|
|
1276
|
-
|
|
1314
|
+
const current = session.sessionId === activeSessionId ? '✅ ' : '';
|
|
1315
|
+
keyboard.text(`${current}${mark} ${truncate(sessionTitle(session, locale), 34)}`, `s:${session.sessionId}`).row();
|
|
1277
1316
|
}
|
|
1278
1317
|
keyboard.text(t(locale, 'newSession'), 'new').row();
|
|
1279
1318
|
keyboard.text(t(locale, 'backToWorkspaces'), 'menu:workspaces');
|
|
1319
|
+
const lines = [workspace.title, visible.length === 0 ? t(locale, 'noSessions') : t(locale, 'selectSession')];
|
|
1320
|
+
if (visible.length > 0)
|
|
1321
|
+
lines.push('', t(locale, 'sessionLegend'));
|
|
1280
1322
|
return {
|
|
1281
|
-
text:
|
|
1323
|
+
text: lines.join('\n'),
|
|
1282
1324
|
keyboard,
|
|
1283
1325
|
};
|
|
1284
1326
|
}
|
|
@@ -1337,8 +1379,9 @@ async function activateSession(runtime, chatId, userId, workspace, sessionId, ti
|
|
|
1337
1379
|
}
|
|
1338
1380
|
async function chooseWorkspace(runtime, chatId, userId, workspace, locale) {
|
|
1339
1381
|
const sessions = await listSessions(runtime, workspace);
|
|
1340
|
-
|
|
1341
|
-
|
|
1382
|
+
const visible = visibleSessions(sessions);
|
|
1383
|
+
const only = visible.length === 1 ? visible[0] : visible.length === 0 && sessions.length === 1 ? sessions[0] : undefined;
|
|
1384
|
+
if (only !== undefined) {
|
|
1342
1385
|
return activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale);
|
|
1343
1386
|
}
|
|
1344
1387
|
await runtime.store.set({
|
|
@@ -1352,7 +1395,17 @@ async function chooseWorkspace(runtime, chatId, userId, workspace, locale) {
|
|
|
1352
1395
|
return buildSessionsView(workspace, sessions, locale);
|
|
1353
1396
|
}
|
|
1354
1397
|
async function createSessionForWorkspace(runtime, chatId, userId, workspace, locale, prompt) {
|
|
1355
|
-
|
|
1398
|
+
// Reuse an existing draft instead of minting another blank Session on every
|
|
1399
|
+
// press of "New session". The controller falls back to a new identity when
|
|
1400
|
+
// the named Session is no longer reusable.
|
|
1401
|
+
const binding = runtime.store.get(String(chatId));
|
|
1402
|
+
const sessions = await listSessions(runtime, workspace);
|
|
1403
|
+
const draft = sessions.find(session => session.blank && session.sessionId === binding?.activeSessionId)
|
|
1404
|
+
?? sessions.find(session => session.blank);
|
|
1405
|
+
const created = await runtime.sessions.create({
|
|
1406
|
+
workspaceId: workspace.id,
|
|
1407
|
+
...(draft === undefined ? {} : { sessionId: draft.sessionId }),
|
|
1408
|
+
});
|
|
1356
1409
|
return activateSession(runtime, chatId, userId, workspace, created.sessionId, t(locale, 'newSessionTitle'), locale, prompt);
|
|
1357
1410
|
}
|
|
1358
1411
|
async function editOrReply(grammyCtx, text, keyboard) {
|
|
@@ -1527,6 +1580,11 @@ async function handleSessionEvent(runtime, session, event) {
|
|
|
1527
1580
|
void maybeWarnLowBalance(runtime, chatId, locale, silent);
|
|
1528
1581
|
break;
|
|
1529
1582
|
}
|
|
1583
|
+
case 'compaction/end':
|
|
1584
|
+
// Compaction can also be started from Web; drop the cached percentage
|
|
1585
|
+
// so the next menu reads the updated projection immediately.
|
|
1586
|
+
runtime.contextCache.delete(session.id);
|
|
1587
|
+
break;
|
|
1530
1588
|
default:
|
|
1531
1589
|
break;
|
|
1532
1590
|
}
|
|
@@ -1669,6 +1727,14 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
|
|
|
1669
1727
|
});
|
|
1670
1728
|
return;
|
|
1671
1729
|
}
|
|
1730
|
+
// Event-driven messages (progress, final answer, questions) read the
|
|
1731
|
+
// binding locale, while handlers read the update. Keep the binding in sync
|
|
1732
|
+
// so changing the Telegram interface language takes effect immediately.
|
|
1733
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1734
|
+
const binding = store.get(grammyCtx.chat.id);
|
|
1735
|
+
if (binding !== undefined && binding.locale !== locale) {
|
|
1736
|
+
await store.set({ ...binding, locale, updatedAt: Date.now() });
|
|
1737
|
+
}
|
|
1672
1738
|
await next();
|
|
1673
1739
|
});
|
|
1674
1740
|
bot.command('start', async (grammyCtx) => {
|
|
@@ -1841,7 +1907,7 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
|
|
|
1841
1907
|
return;
|
|
1842
1908
|
}
|
|
1843
1909
|
const sessionsForWorkspace = await listSessions(runtime, workspace);
|
|
1844
|
-
const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
|
|
1910
|
+
const view = buildSessionsView(workspace, sessionsForWorkspace, locale, binding?.activeSessionId);
|
|
1845
1911
|
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1846
1912
|
});
|
|
1847
1913
|
bot.callbackQuery('menu:refresh', async (grammyCtx) => {
|
|
@@ -2131,7 +2197,8 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
|
|
|
2131
2197
|
return;
|
|
2132
2198
|
}
|
|
2133
2199
|
const sessionsForWorkspace = await listSessions(runtime, workspace);
|
|
2134
|
-
|
|
2200
|
+
const visibleForWorkspace = visibleSessions(sessionsForWorkspace);
|
|
2201
|
+
if (visibleForWorkspace.length === 0) {
|
|
2135
2202
|
try {
|
|
2136
2203
|
const view = await createSessionForWorkspace(runtime, chatId, userId, workspace, locale, { text, messageId });
|
|
2137
2204
|
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
@@ -2146,14 +2213,14 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
|
|
|
2146
2213
|
}
|
|
2147
2214
|
return;
|
|
2148
2215
|
}
|
|
2149
|
-
if (
|
|
2150
|
-
const only =
|
|
2216
|
+
if (visibleForWorkspace.length === 1) {
|
|
2217
|
+
const only = visibleForWorkspace[0];
|
|
2151
2218
|
const view = await activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale, { text, messageId });
|
|
2152
2219
|
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
2153
2220
|
return;
|
|
2154
2221
|
}
|
|
2155
2222
|
runtime.pendingPrompt.set(chatId, { text, messageId });
|
|
2156
|
-
const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
|
|
2223
|
+
const view = buildSessionsView(workspace, sessionsForWorkspace, locale, binding?.activeSessionId);
|
|
2157
2224
|
await grammyCtx.reply(`${view.text}\n\n${t(locale, 'pendingText')}`, { reply_markup: view.keyboard });
|
|
2158
2225
|
});
|
|
2159
2226
|
bot.catch((error) => {
|