dsh-tg-bridge 1.49.0 → 1.50.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.
@@ -12,6 +12,7 @@ import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } fro
12
12
  import { DSH_HOME, LOG } from '../core/paths.mjs';
13
13
  import { approvals, enqueue, lastPrompt, redeliver, rewindUsed } from '../turn/queue.mjs';
14
14
  import { handleBranchPress } from './branch-press.mjs';
15
+ import { handleRegenPress } from './regen-press.mjs';
15
16
  import { answerRewindPress, cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
16
17
  import { applyRewind, newestBackup, restoreBackup } from '../work/rewind.mjs';
17
18
  import { diffPressRouter } from '../control/cmd-diff.mjs';
@@ -180,6 +181,8 @@ export async function handleCallback(query) {
180
181
 
181
182
  if (await handleBranchPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log })) return;
182
183
 
184
+ if (await handleRegenPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log })) return;
185
+
183
186
  // A search result's plus button. The name came from the registry and the
184
187
  // command is the one the hint under the list names, so a tap installs exactly
185
188
  // what was read — no hidden second path into pnpm.
@@ -19,7 +19,7 @@ export const CONTROL_COMMANDS = [
19
19
  'skills', 'soul', 'remember', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
20
20
  'prices', 'cost', 'balance', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
21
21
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
22
- 'rewind', 'fork', 'branches', 'branch', 'history', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
22
+ 'rewind', 'fork', 'branches', 'branch', 'history', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start', 'regen',
23
23
  'ls', 'view', 'edit', 'subagents',
24
24
  ];
25
25
 
@@ -20,7 +20,7 @@ export const DOC_URL = 'https://github.com/aleksvega/dsh-tg-bridge/blob/master/d
20
20
  export const HELP_SECTIONS = [
21
21
  { id: 'work', commands: ['start', 'cd', 'ls', 'view', 'edit', 'new', 'stop', 'send', 'seed', 'diff', 'find'] },
22
22
  { id: 'goals', commands: ['goal', 'tasks'] },
23
- { id: 'sessions', commands: ['status', 'sessions', 'rewind', 'branch', 'history', 'profile', 'compact', 'card'] },
23
+ { id: 'sessions', commands: ['status', 'sessions', 'rewind', 'regen', 'branch', 'history', 'profile', 'compact', 'card'] },
24
24
  { id: 'model', commands: ['model', 'effort', 'prices', 'cost', 'balance', 'thoughts', 'fallback', 'endpoint', 'load'] },
25
25
  { id: 'agents', commands: ['agents', 'crew', 'subagents', 'preset', 'plan', 'permissions'] },
26
26
  { id: 'tuning', commands: ['jobs', 'remind', 'every'] },
@@ -16,7 +16,7 @@ import { CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './commands-registry.mjs';
16
16
  */
17
17
  const SECTIONS = {
18
18
  work: ['cd', 'ls', 'view', 'edit', 'seed', 'send', 'diff'],
19
- session: ['sessions', 'rewind', 'branch', 'history', 'profile', 'agents', 'subagents'],
19
+ session: ['sessions', 'rewind', 'regen', 'branch', 'history', 'profile', 'agents', 'subagents'],
20
20
  goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
21
  talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'balance', 'lang', 'endpoint', 'fallback'],
22
22
  ext: ['plugins', 'mcp', 'skills', 'soul', 'remember', 'preset', 'permissions', 'crew'],
@@ -0,0 +1,41 @@
1
+ // The ↻ press's router half, out of the callback router for the same two
2
+ // reasons as the branch picker's: the router sits at the size ceiling, and the
3
+ // press is one idea — check the card against the live session, then type
4
+ // `/regen`, which stays the only implementation of a regeneration.
5
+ import { isRegenPress, regenPressState } from '../work/regen.mjs';
6
+ import { t } from '../core/i18n.mjs';
7
+ import { DSH_HOME } from '../core/paths.mjs';
8
+ import { state } from '../core/state.mjs';
9
+ import { tg } from './telegram.mjs';
10
+ import { sessionFile } from './thoughts.mjs';
11
+ import { activeTurns } from '../turn/turn.mjs';
12
+ import { join } from 'node:path';
13
+
14
+ /**
15
+ * Handle one `rg:` press.
16
+ *
17
+ * @returns {Promise<boolean>} true when the press was this module's to answer.
18
+ */
19
+ export async function handleRegenPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log }) {
20
+ if (!isRegenPress(data)) return false;
21
+ const sessionId = state.sessions[key] || '';
22
+ const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
23
+ const check = regenPressState(data, { sessionId, busy: activeTurns.has(key), file: sessionPath });
24
+ if (check.verdict === 'ok') {
25
+ await clearKeyboard();
26
+ await answer(t(lang, 'bridge.cb.done'));
27
+ await runCommandFromButton('/regen', { chatId, threadId, key, lang });
28
+ } else {
29
+ // One line replaces the card: a stale card keeps nothing clickable.
30
+ await tg('editMessageText', {
31
+ chat_id: chatId,
32
+ message_id: messageId,
33
+ text: t(lang, check.verdict === 'busy' ? 'ctrl.rewind.busy' : 'ctrl.rewind.stale'),
34
+ reply_markup: { inline_keyboard: [] },
35
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
36
+ }).catch(() => {});
37
+ await answer(t(lang, 'bridge.cb.done'));
38
+ }
39
+ log(`regen press ${data} for ${key}`);
40
+ return true;
41
+ }
@@ -16,7 +16,8 @@ import { parseReminder, stampAt, upcoming } from '../work/reminders.mjs';
16
16
  import { AgentsetStore, emptySet, slugId } from '../profile/agentsets.mjs';
17
17
  import { SETTINGS_PAGES, renderSettingsCard, settingsCurrent } from '../profile/settings-card.mjs';
18
18
  import { sessionKey } from '../core/keys.mjs';
19
- import { applyFork, allTurns, branchTarget, planFork, planRewind } from '../work/rewind.mjs';
19
+ import { applyFork, applyRewind, allTurns, branchTarget, planFork, planRewind, recentTurns } from '../work/rewind.mjs';
20
+ import { syntheticMessage } from '../work/schedules.mjs';
20
21
  import { formatHistory, writeHistory } from '../work/history.mjs';
21
22
  import { cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
22
23
  import { renderRewindCard, renderRewindUsage } from '../work/rewind-card.mjs';
@@ -113,6 +114,42 @@ export async function handleSessionCommands(ctx) {
113
114
  say(res ? t(lang, 'ctrl.seed.done', { id: res }) : t(lang, 'ctrl.seed.failed'));
114
115
  return true;
115
116
  }
117
+ case '/regen': {
118
+ // The desktop's retry on the last FINISHED turn. The exchange leaves the
119
+ // session — a copy of it sitting above the same question asked again is
120
+ // history nobody wrote — and the question comes back as a fresh message,
121
+ // so the answer is regenerated by the same turn machinery, not replayed.
122
+ // Attachments do not repeat: a turn whose only content was a file has no
123
+ // question to re-ask, and the refusal says so instead of guessing.
124
+ const sessionId = state.sessions[key] || '';
125
+ if (!sessionId) { say(t(lang, 'ctrl.fork.noSession')); return true; }
126
+ if (ctx.activeTurns && ctx.activeTurns.has(key)) { say(t(lang, 'ctrl.rewind.busy')); return true; }
127
+ if (typeof ctx.redeliver !== 'function') { say(t(lang, 'ctrl.remember.noTurn')); return true; }
128
+ const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
129
+ // Parsing and cutting the session is quiet disk work: say it started
130
+ // before doing it, so the pause is an answer, not silence.
131
+ say(t(lang, 'ctrl.regen.working'));
132
+ const last = recentTurns(file, { limit: 1 })[0];
133
+ if (!last) { say(t(lang, 'ctrl.rewind.refused.no-turns', { total: 0, dropped: 1 })); return true; }
134
+ if (!String(last.user || '').trim()) { say(t(lang, 'ctrl.regen.noText')); return true; }
135
+ const plan = planRewind(file, 1);
136
+ if (plan.reason) {
137
+ say(t(lang, `ctrl.rewind.refused.${plan.reason}`, { total: plan.total, dropped: 1 }));
138
+ return true;
139
+ }
140
+ let backup = '';
141
+ try {
142
+ backup = applyRewind(file, plan.offset, plan.size);
143
+ } catch (error) {
144
+ say(t(lang, 'ctrl.fork.failed', { error: error.message }));
145
+ return true;
146
+ }
147
+ const owner = config?.allowedUserIds?.[0] ?? ctx.chatId;
148
+ ctx.redeliver(key, syntheticMessage({ chatId: ctx.chatId, threadId: ctx.threadId, text: String(last.user) }, owner));
149
+ log(`regen cut turn ${last.turn} of ${sessionId} (backup ${backup}) and re-asked for ${key}`);
150
+ // No second line: the new turn's own card is the confirmation.
151
+ return true;
152
+ }
116
153
  case '/rewind': {
117
154
  // Going back the way the desktop app's branch-from-here does. The file is
118
155
  // cut only where a turn begins, a copy of it is kept, and a turn that is
@@ -162,6 +199,9 @@ export async function handleSessionCommands(ctx) {
162
199
  const wanted = String(arg || '').trim().toLowerCase();
163
200
  const steps = wanted ? Number.parseInt(wanted, 10) : 0;
164
201
  if (wanted && (!Number.isInteger(steps) || steps < 0)) { say(t(lang, 'ctrl.fork.usage')); return true; }
202
+ // The copy is quiet disk work on a file that can be tens of MB: say it
203
+ // started before doing it, so the pause is an answer, not silence.
204
+ say(t(lang, 'ctrl.fork.working'));
165
205
  const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
166
206
  const plan = planFork(file, steps);
167
207
  if (plan.reason) {
@@ -210,6 +250,10 @@ export async function handleSessionCommands(ctx) {
210
250
  const source = target.kind === 'here' ? target.id : here;
211
251
  if (!source) { say(t(lang, 'ctrl.fork.noSession')); return true; }
212
252
  if (target.kind === 'topic' && !ctx.openTopic) { say(t(lang, 'ctrl.branch.unsupported')); return true; }
253
+ // Reading and copying the session is seconds of quiet on a big file, and
254
+ // a new topic adds a Telegram roundtrip on top: the ack line is the
255
+ // answer for that pause, sent before the work starts.
256
+ say(t(lang, 'ctrl.branch.working'));
213
257
  const file = sessionFile(join(DSH_HOME, 'sessions'), source);
214
258
  // `steps` is 0 for every form but `new <n>`: a branch into another topic
215
259
  // copies the whole session unless the person named a turn to branch from.
@@ -266,6 +310,9 @@ export async function handleSessionCommands(ctx) {
266
310
  // document, small enough to carry, big enough to hold a thousand turns.
267
311
  const id = state.sessions[key] || '';
268
312
  if (!id) { say(t(lang, 'ctrl.history.noSession')); return true; }
313
+ // allTurns parses the whole session file, and a thousand-turn topic is
314
+ // not instant: the ack line answers for that pause before it starts.
315
+ say(t(lang, 'ctrl.history.working'));
269
316
  const turns = allTurns(sessionFile(join(DSH_HOME, 'sessions'), id));
270
317
  if (!turns.length) { say(t(lang, 'ctrl.history.empty')); return true; }
271
318
  const short = id.slice(8, 16);
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.50.0
4
+
5
+ - **↻ — the last answer, asked again.** Every finished turn's card now opens a
6
+ `↻` row above the file buttons, and `/regen` does the same from the keyboard:
7
+ the exchange leaves the session the way `/rewind 1` would (a backup copy
8
+ stays), and the question is fed back through the queue as a fresh message
9
+ from the person — so the new answer is generated by the same machinery, not
10
+ replayed from history. The button carries the turn number and the session
11
+ tail, and the press re-reads both from the live file: a card left behind by
12
+ an older turn of the same session answers "the card is stale" instead of
13
+ cutting the wrong turn, and a topic that moved to another session, or is
14
+ running a turn right now, is refused with the sentences the rewind commands
15
+ already use. A turn whose only content was an attachment is not re-asked as
16
+ empty text — the refusal says to send the file again, because attachments
17
+ do not repeat. The ↻ row is built where the file rows are, so the finished
18
+ card stays one keyboard; the router half of the press lives beside the
19
+ branch picker's, and `/regen` stays the only implementation of a
20
+ regeneration. Three locales, 6 tests.
21
+
22
+ - **The heavy session commands answer before the disk work.** `/fork`, `/branch`
23
+ and `/history` now say "working" the moment the request passes the cheap
24
+ checks, instead of going quiet for the seconds a session copy or a topic
25
+ history takes to read: the pause after a command is now an answer, not
26
+ silence. Refusals that cost nothing to know — no session, busy, unsupported —
27
+ still answer in one line and nothing else.
28
+
3
29
  ## 1.49.0
4
30
 
5
31
  - **Branching from any turn, as a tap instead of a count.** The `/rewind`
package/docs/COMMANDS.md CHANGED
@@ -33,6 +33,7 @@ Built from the same code as `/help`: the list, the sections and the sentences ar
33
33
  - `/status` — Where this topic stands: session, model, effort, running turns. Read-only.
34
34
  - `/sessions` — The sessions of this topic. /sessions lists the last few with the id to copy; /sessions <id> continues an older one here. /new starts a fresh one and leaves the old on disk.
35
35
  - `/rewind` — Going back, one command with three words. /rewind 2 removes the last two turns so you can word the task differently: it shows a card of what will go and cuts only on the button; /rewind undo puts it back. /rewind fork [n] is a branch inside this topic: it copies the session as it stood n turns back and moves this topic onto the copy, cutting nothing. /rewind branches lists the copies, a press switches. A branch into another topic is /branch.
36
+ - `/regen` — Ask the last question again: the turn leaves the session (a backup copy stays, as with /rewind) and the question is sent anew. The ↻ button on a finished turn’s card does the same. Attachments do not repeat — only the text of the question.
36
37
  - `/branch` — A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new [n] carries a copy of this session into a new topic — the whole thing, or from n turns back. The 🌿 buttons on the /rewind card offer the same for recent turns. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.
37
38
  - `/history` — Exports this topic’s whole history as one markdown file: turns and answers in order, no tool noise. Easy to read and keep on a phone.
38
39
  - `/profile` — The profile this topic runs on, and how to change it: /profile <name>, /profile new.
@@ -136,6 +137,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
136
137
  - `/status` — Где тема сейчас: сессия, модель, усилие, идущие ходы. Ничего не меняет.
137
138
  - `/sessions` — Сессии этой темы. /sessions показывает последние и id, который можно скопировать; /sessions <id> продолжает старую сессию здесь же. /new начинает новую, старая остаётся на диске.
138
139
  - `/rewind` — Откат — одна команда с тремя словами. /rewind 2 убирает два последних хода, чтобы сформулировать иначе: сначала карточка того, что уйдёт, режет только кнопка; /rewind undo возвращает. /rewind fork [n] — ветка внутри темы: копирует сессию в том виде, каким она была n ходов назад, и переводит тему на копию, ничего не отрезая. /rewind branches показывает копии, нажатие переключает. Ветка в другую тему — это /branch.
140
+ - `/regen` — Переспросить последний ответ: ход убирается из сессии (копия-бэкап остаётся, как у /rewind), и вопрос уходит заново. Кнопка ↻ на карточке законченного хода делает то же. Вложения не повторяются — только текст вопроса.
139
141
  - `/branch` — Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new [n] уносит копию этой сессии в новую тему — целиком или от n ходов назад. Кнопки 🌿 в карточке /rewind предлагают то же для последних ходов. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.
140
142
  - `/history` — Выгружает всю историю темы одним markdown-файлом: ходы и ответы по порядку, без шума инструментов. Удобно читать и хранить на телефоне.
141
143
  - `/profile` — Профиль, на котором идёт тема, и как его сменить: /profile <имя>, /profile new.
@@ -239,6 +241,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
239
241
  - `/status` — 本话题的状态:会话、模型、力度、进行中的轮次。不改变任何东西。
240
242
  - `/sessions` — 本话题的会话。/sessions 列出最近几个和可复制的编号;/sessions <id> 就在这里继续较早的会话。/new 开始新的,旧的留在磁盘上。
241
243
  - `/rewind` — 回退只有一条命令、三种说法。/rewind 2 去掉最后两轮以便换种说法:先显示将移除内容的卡片,只有按按钮才裁切;/rewind undo 可恢复。/rewind fork [n] 是话题内部的分支:把会话复制成 n 轮前的样子并把本话题切到副本,不切断任何东西。/rewind branches 列出副本,按一下就切换。分支到另一个话题用 /branch。
244
+ - `/regen` — 重新提问最后一个回答:该轮次从会话中移除(备份副本保留,与 /rewind 相同),问题重新发送。已完成轮次卡片上的 ↻ 按钮做同样的事。附件不会重复——只有问题的文本。
242
245
  - `/branch` — 分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new [n] 把本会话的副本带到一个新话题——整段,或从 n 轮之前。/rewind 卡片上的 🌿 按钮对最近的轮提供同样的操作。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。
243
246
  - `/history` — 将本话题的全部历史导出为一个 markdown 文件:按顺序排列的回合与回答,不含工具噪音。适合在手机上阅读和保存。
244
247
  - `/profile` — 本话题使用的配置档,以及如何更换:/profile <名称>、/profile new。
@@ -6,6 +6,7 @@
6
6
  export default {
7
7
  'ctrl.help.about.branch': "A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new [n] carries a copy of this session into a new topic — the whole thing, or from n turns back. The 🌿 buttons on the /rewind card offer the same for recent turns. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.",
8
8
  'ctrl.branch.usage': "A branch has two forms. /branch <id> — a copy of that session here, this topic continues it. /branch new [n] — a copy of this session in a new topic, from n turns back (without a number, the whole thing). A copy inside this topic is /rewind fork.",
9
+ 'ctrl.branch.working': "Copying the session…",
9
10
  'ctrl.branch.confirm': "Branch from turn {turn}: the copy keeps the first {kept} turn(s); the original session stays whole. Where should the copy go?",
10
11
  'ctrl.branch.here': "In this topic",
11
12
  'ctrl.branch.new': "New topic",
@@ -16,4 +17,16 @@ export default {
16
17
  'ctrl.branch.seed': "A branch of \"{name}\": a copy of the session, {kept} turn(s). Work here — the original topic is untouched.",
17
18
  'ctrl.branch.suffix': "branch",
18
19
  'ctrl.branch.untitled': "Untitled",
20
+ // The fork family moved here from ctrl.mjs: a fork is a branch that stays in
21
+ // this topic, and the ctrl table was at the 500-line ceiling.
22
+ 'ctrl.fork.done': "Branched: this topic now continues in {id}, keeping {kept} turn(s). The old session is untouched — /rewind branches lists both.",
23
+ 'ctrl.fork.noSession': "This topic has no session yet: the first message starts one.",
24
+ 'ctrl.fork.busy': "A turn is running in this topic. A run writes its session, so branch after it finishes.",
25
+ 'ctrl.fork.usage': "Usage: /rewind fork — a copy from here, or /rewind fork 2 — a copy from two turns back.",
26
+ 'ctrl.fork.working': "Copying the session…",
27
+ 'ctrl.fork.failed': "Could not branch: {error}",
28
+ 'ctrl.fork.none': "No branches in this topic yet. /rewind fork makes one.",
29
+ 'ctrl.fork.list': "{n} branch(es) of this topic:",
30
+ 'ctrl.fork.current': "This topic is on {id}.",
31
+ 'ctrl.fork.turns': "{n} turn(s)",
19
32
  };
package/i18n/en/ctrl.mjs CHANGED
@@ -107,15 +107,8 @@ export default {
107
107
  'ctrl.rewind.refused.too-many-steps': "The session has {total} turn(s); going back {dropped} would leave nothing to continue from. Use /new for a fresh session.",
108
108
  'ctrl.rewind.refused.would-leave-open-turn': "The session boundary does not fall where a turn ends; nothing was removed.",
109
109
  'ctrl.rewind.refused.no-header': "The session file has no header record to keep; nothing was removed.",
110
- 'ctrl.fork.done': "Branched: this topic now continues in {id}, keeping {kept} turn(s). The old session is untouched — /rewind branches lists both.",
111
- 'ctrl.fork.noSession': "This topic has no session yet: the first message starts one.",
112
- 'ctrl.fork.busy': "A turn is running in this topic. A run writes its session, so branch after it finishes.",
113
- 'ctrl.fork.usage': "Usage: /rewind fork — a copy from here, or /rewind fork 2 — a copy from two turns back.",
114
- 'ctrl.fork.failed': "Could not branch: {error}",
115
- 'ctrl.fork.none': "No branches in this topic yet. /rewind fork makes one.",
116
- 'ctrl.fork.list': "{n} branch(es) of this topic:",
117
- 'ctrl.fork.current': "This topic is on {id}.",
118
- 'ctrl.fork.turns': "{n} turn(s)",
110
+ // The ctrl.fork.* family lives in branch.mjs with the rest of branching: a
111
+ // fork is a branch that stays in this topic, and ctrl.mjs sat on the ceiling.
119
112
  'menu.cmd.new': "A new session in this topic",
120
113
  'menu.cmd.status': "What is running: session, model, turn",
121
114
  'menu.cmd.sessions': "The sessions of this topic, and switching between them",
@@ -4,6 +4,7 @@
4
4
  export default {
5
5
  'ctrl.help.about.history': 'Exports this topic\u2019s whole history as one markdown file: turns and answers in order, no tool noise. Easy to read and keep on a phone.',
6
6
  'ctrl.history.noSession': 'There is no session in this topic yet \u2014 no history to export.',
7
+ 'ctrl.history.working': 'Collecting the topic history into a file…',
7
8
  'ctrl.history.empty': 'The session has no turns yet.',
8
9
  'ctrl.history.title': 'History \u00b7 session {id} \u00b7 {n} turn(s)',
9
10
  'ctrl.history.turn': 'Turn',
@@ -0,0 +1,9 @@
1
+ // EN strings for regenerating the last answer.
2
+ //
3
+ // Same table format as branch.mjs — one feature, one file, one diff.
4
+ export default {
5
+ 'ctrl.help.about.regen': 'Ask the last question again: the turn leaves the session (a backup copy stays, as with /rewind) and the question is sent anew. The ↻ button on a finished turn\u2019s card does the same. Attachments do not repeat — only the text of the question.',
6
+ 'ctrl.regen.working': '↻ Dropping the last turn and asking again…',
7
+ 'ctrl.regen.noText': 'The last turn has no question text — only an attachment. Send the attachment as a new message.',
8
+ 'btn.regen': 'Ask again',
9
+ };
package/i18n/en.mjs CHANGED
@@ -21,4 +21,5 @@ import balance from './en/balance.mjs';
21
21
  import branch from './en/branch.mjs';
22
22
  import history from './en/history.mjs';
23
23
  import remember from './en/remember.mjs';
24
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember };
24
+ import regen from './en/regen.mjs';
25
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
@@ -6,6 +6,7 @@
6
6
  export default {
7
7
  'ctrl.help.about.branch': "Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new [n] уносит копию этой сессии в новую тему — целиком или от n ходов назад. Кнопки 🌿 в карточке /rewind предлагают то же для последних ходов. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.",
8
8
  'ctrl.branch.usage': "Ветка — две формы. /branch <id> — копия той сессии сюда, эта тема продолжит её. /branch new [n] — копия этой сессии в новую тему, от n ходов назад (без числа — целиком). Копия внутри этой темы — /rewind fork.",
9
+ 'ctrl.branch.working': "Копирую сессию…",
9
10
  'ctrl.branch.confirm': "Ветка от хода {turn}: в копии первые {kept} ход(ов), исходная сессия останется целой. Куда унести копию?",
10
11
  'ctrl.branch.here': "В эту тему",
11
12
  'ctrl.branch.new': "В новую тему",
@@ -16,4 +17,16 @@ export default {
16
17
  'ctrl.branch.seed': "Ветка от темы «{name}»: копия сессии, {kept} ход(ов). Работай здесь — исходная тема не тронута.",
17
18
  'ctrl.branch.suffix': "ветка",
18
19
  'ctrl.branch.untitled': "Без названия",
20
+ // The fork family moved here from ctrl.mjs: a fork is a branch that stays in
21
+ // this topic, and the ctrl table was at the 500-line ceiling.
22
+ 'ctrl.fork.done': "Ветка создана: тема продолжается в {id}, сохранено {kept} ход(ов). Старая сессия цела — обе видны в /rewind branches.",
23
+ 'ctrl.fork.noSession': "В этой теме ещё нет сессии: её начнёт первое сообщение.",
24
+ 'ctrl.fork.busy': "В теме идёт ход. Он пишет свою сессию — ветвить надо после него.",
25
+ 'ctrl.fork.usage': "Как это работает: /rewind fork — копия отсюда, /rewind fork 2 — копия с двух ходов назад.",
26
+ 'ctrl.fork.working': "Копирую сессию…",
27
+ 'ctrl.fork.failed': "Ветку создать не удалось: {error}",
28
+ 'ctrl.fork.none': "В этой теме ещё нет веток. Создать: /rewind fork.",
29
+ 'ctrl.fork.list': "Ветки этой темы: {n}",
30
+ 'ctrl.fork.current': "Тема сейчас на {id}.",
31
+ 'ctrl.fork.turns': "{n} ход(ов)",
19
32
  };
package/i18n/ru/ctrl.mjs CHANGED
@@ -107,15 +107,8 @@ export default {
107
107
  'ctrl.rewind.refused.too-many-steps': "В сессии {total} ход(ов); откат на {dropped} не оставит ничего. Для чистой сессии — /new.",
108
108
  'ctrl.rewind.refused.would-leave-open-turn': "Граница сессии не совпала с концом хода; ничего не удалено.",
109
109
  'ctrl.rewind.refused.no-header': "В файле сессии нет шапки, которую надо сохранить; ничего не удалено.",
110
- 'ctrl.fork.done': "Ветка создана: тема продолжается в {id}, сохранено {kept} ход(ов). Старая сессия цела — обе видны в /rewind branches.",
111
- 'ctrl.fork.noSession': "В этой теме ещё нет сессии: её начнёт первое сообщение.",
112
- 'ctrl.fork.busy': "В теме идёт ход. Он пишет свою сессию — ветвить надо после него.",
113
- 'ctrl.fork.usage': "Как это работает: /rewind fork — копия отсюда, /rewind fork 2 — копия с двух ходов назад.",
114
- 'ctrl.fork.failed': "Ветку создать не удалось: {error}",
115
- 'ctrl.fork.none': "В этой теме ещё нет веток. Создать: /rewind fork.",
116
- 'ctrl.fork.list': "Ветки этой темы: {n}",
117
- 'ctrl.fork.current': "Тема сейчас на {id}.",
118
- 'ctrl.fork.turns': "{n} ход(ов)",
110
+ // The ctrl.fork.* family lives in branch.mjs with the rest of branching: a
111
+ // fork is a branch that stays in this topic, and ctrl.mjs sat on the ceiling.
119
112
  'menu.cmd.new': "Новая сессия в этой теме",
120
113
  'menu.cmd.status': "Что сейчас: сессия, модель, активный ход",
121
114
  'menu.cmd.sessions': "Сессии этой темы и переключение между ними",
@@ -4,6 +4,7 @@
4
4
  export default {
5
5
  'ctrl.help.about.history': 'Выгружает всю историю темы одним markdown-файлом: ходы и ответы по порядку, без шума инструментов. Удобно читать и хранить на телефоне.',
6
6
  'ctrl.history.noSession': 'В этой теме ещё нет сессии — историю брать неоткуда.',
7
+ 'ctrl.history.working': 'Собираю историю темы в файл…',
7
8
  'ctrl.history.empty': 'В сессии ещё нет ходов.',
8
9
  'ctrl.history.title': 'История · сессия {id} · {n} ход(ов)',
9
10
  'ctrl.history.turn': 'Ход',
@@ -0,0 +1,9 @@
1
+ // RU strings for regenerating the last answer.
2
+ //
3
+ // Same table format as branch.mjs — one feature, one file, one diff.
4
+ export default {
5
+ 'ctrl.help.about.regen': 'Переспросить последний ответ: ход убирается из сессии (копия-бэкап остаётся, как у /rewind), и вопрос уходит заново. Кнопка ↻ на карточке законченного хода делает то же. Вложения не повторяются — только текст вопроса.',
6
+ 'ctrl.regen.working': '↻ Убираю последний ход и переспрашиваю…',
7
+ 'ctrl.regen.noText': 'У последнего хода нет текста вопроса — только вложение. Перешли вложение новым сообщением.',
8
+ 'btn.regen': 'Переспросить',
9
+ };
package/i18n/ru.mjs CHANGED
@@ -21,4 +21,5 @@ import balance from './ru/balance.mjs';
21
21
  import branch from './ru/branch.mjs';
22
22
  import history from './ru/history.mjs';
23
23
  import remember from './ru/remember.mjs';
24
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember };
24
+ import regen from './ru/regen.mjs';
25
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
@@ -6,6 +6,7 @@
6
6
  export default {
7
7
  'ctrl.help.about.branch': "分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new [n] 把本会话的副本带到一个新话题——整段,或从 n 轮之前。/rewind 卡片上的 🌿 按钮对最近的轮提供同样的操作。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。",
8
8
  'ctrl.branch.usage': "分支有两种形式。/branch <id> —— 把那个会话的副本带到这里,本话题接着它走。/branch new [n] —— 把本会话的副本放到一个新话题,从 n 轮之前(不带数字则整段)。在本话题内部复制用 /rewind fork。",
9
+ 'ctrl.branch.working': "正在复制会话……",
9
10
  'ctrl.branch.confirm': "从第 {turn} 轮分支:副本保留前 {kept} 轮,原会话保持完好。副本放到哪里?",
10
11
  'ctrl.branch.here': "在本话题",
11
12
  'ctrl.branch.new': "新话题",
@@ -16,4 +17,16 @@ export default {
16
17
  'ctrl.branch.seed': "来自话题「{name}」的分支:会话的副本,{kept} 轮。在这里工作——原话题未改动。",
17
18
  'ctrl.branch.suffix': "分支",
18
19
  'ctrl.branch.untitled': "未命名",
20
+ // The fork family moved here from ctrl.mjs: a fork is a branch that stays in
21
+ // this topic, and the ctrl table was at the 500-line ceiling.
22
+ 'ctrl.fork.done': "已建立分支:本话题继续在 {id},保留 {kept} 轮。原会话完好——用 /rewind branches 查看两者。",
23
+ 'ctrl.fork.noSession': "本话题还没有会话:第一条消息会开启它。",
24
+ 'ctrl.fork.busy': "本话题正在进行一轮。它会写入会话,请在结束后再分支。",
25
+ 'ctrl.fork.usage': "用法:/rewind fork 从这里复制,/rewind fork 2 从两轮前复制。",
26
+ 'ctrl.fork.working': "正在复制会话……",
27
+ 'ctrl.fork.failed': "无法建立分支:{error}",
28
+ 'ctrl.fork.none': "本话题还没有分支。用 /rewind fork 创建。",
29
+ 'ctrl.fork.list': "本话题的分支:{n}",
30
+ 'ctrl.fork.current': "本话题当前在 {id}。",
31
+ 'ctrl.fork.turns': "{n} 轮",
19
32
  };
package/i18n/zh/ctrl.mjs CHANGED
@@ -107,15 +107,8 @@ export default {
107
107
  'ctrl.rewind.refused.too-many-steps': "本会话共有 {total} 轮;回退 {dropped} 轮将没有可继续的内容。需要全新的会话请用 /new。",
108
108
  'ctrl.rewind.refused.would-leave-open-turn': "会话边界不在轮次结束处;没有删除任何内容。",
109
109
  'ctrl.rewind.refused.no-header': "会话文件没有可保留的头部记录;没有删除任何内容。",
110
- 'ctrl.fork.done': "已建立分支:本话题继续在 {id},保留 {kept} 轮。原会话完好——用 /rewind branches 查看两者。",
111
- 'ctrl.fork.noSession': "本话题还没有会话:第一条消息会开启它。",
112
- 'ctrl.fork.busy': "本话题正在进行一轮。它会写入会话,请在结束后再分支。",
113
- 'ctrl.fork.usage': "用法:/rewind fork 从这里复制,/rewind fork 2 从两轮前复制。",
114
- 'ctrl.fork.failed': "无法建立分支:{error}",
115
- 'ctrl.fork.none': "本话题还没有分支。用 /rewind fork 创建。",
116
- 'ctrl.fork.list': "本话题的分支:{n}",
117
- 'ctrl.fork.current': "本话题当前在 {id}。",
118
- 'ctrl.fork.turns': "{n} 轮",
110
+ // The ctrl.fork.* family lives in branch.mjs with the rest of branching: a
111
+ // fork is a branch that stays in this topic, and ctrl.mjs sat on the ceiling.
119
112
  'menu.cmd.new': "在此话题新建会话",
120
113
  'menu.cmd.status': "当前状态:会话、模型、轮次",
121
114
  'menu.cmd.sessions': "本话题的会话与切换",
@@ -4,6 +4,7 @@
4
4
  export default {
5
5
  'ctrl.help.about.history': '将本话题的全部历史导出为一个 markdown 文件:按顺序排列的回合与回答,不含工具噪音。适合在手机上阅读和保存。',
6
6
  'ctrl.history.noSession': '本话题还没有会话——没有可导出的历史。',
7
+ 'ctrl.history.working': '正在把话题历史整理成文件……',
7
8
  'ctrl.history.empty': '会话中还没有任何回合。',
8
9
  'ctrl.history.title': '历史记录 · 会话 {id} · {n} 回合',
9
10
  'ctrl.history.turn': '回合',
@@ -0,0 +1,9 @@
1
+ // ZH strings for regenerating the last answer.
2
+ //
3
+ // Same table format as branch.mjs — one feature, one file, one diff.
4
+ export default {
5
+ 'ctrl.help.about.regen': '重新提问最后一个回答:该轮次从会话中移除(备份副本保留,与 /rewind 相同),问题重新发送。已完成轮次卡片上的 ↻ 按钮做同样的事。附件不会重复——只有问题的文本。',
6
+ 'ctrl.regen.working': '↻ 正在移除最后一轮并重新提问……',
7
+ 'ctrl.regen.noText': '最后一轮没有问题文本——只有附件。请把附件作为新消息重新发送。',
8
+ 'btn.regen': '重问',
9
+ };
package/i18n/zh.mjs CHANGED
@@ -21,4 +21,5 @@ import balance from './zh/balance.mjs';
21
21
  import branch from './zh/branch.mjs';
22
22
  import history from './zh/history.mjs';
23
23
  import remember from './zh/remember.mjs';
24
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember };
24
+ import regen from './zh/regen.mjs';
25
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...mcp, ...plan, ...dsh, ...supervision, ...files, ...balance, ...branch, ...history, ...remember, ...regen };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.49.0",
3
+ "version": "1.50.0",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/turn/files.mjs CHANGED
@@ -10,6 +10,8 @@
10
10
  // forty, and a card offering to send them would be a file manager nobody asked
11
11
  // for.
12
12
  import { extname } from 'node:path';
13
+ import { regenRow } from '../work/regen.mjs';
14
+ import { sessionFile } from '../chat/thoughts.mjs';
13
15
 
14
16
  /**
15
17
  * Tools that leave a file behind, in the shape each one names its target.
@@ -93,3 +95,28 @@ export function fileKeyboard(files, lang, t) {
93
95
  callback_data: `tf:${index}`,
94
96
  }]);
95
97
  }
98
+
99
+ /**
100
+ * The whole keyboard of a finished turn's card: the ↻ row first, file rows
101
+ * under it. Kept here so the card's attachments stay one idea — the turn says
102
+ * what it did, and the buttons offer to redo it or send the files.
103
+ *
104
+ * `state.turnFiles` is written for the press resolver before the rows are
105
+ * returned, because a keyboard whose numbers resolve to nothing is a button
106
+ * that fails on tap. The ↻ row needs no state: its callback carries the turn
107
+ * number and the session tail, and the press re-reads both from the session.
108
+ */
109
+ export function finalKeyboard({ calls = [], state, key, save, lang, t, sessionId = '', sessionsRoot = '' }) {
110
+ const files = turnFiles(calls);
111
+ const rows = [];
112
+ const regen = sessionId && sessionsRoot
113
+ ? regenRow(sessionId, sessionFile(sessionsRoot, sessionId), lang, t)
114
+ : [];
115
+ if (regen.length) rows.push(regen);
116
+ if (files.length) {
117
+ state.turnFiles = { ...(state.turnFiles || {}), [key]: files };
118
+ save();
119
+ rows.push(...fileKeyboard(files, lang, t));
120
+ }
121
+ return rows;
122
+ }
package/turn/progress.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  import { mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
10
  import { config, log, saveState as saveStateNow, state } from '../core/state.mjs';
11
- import { THOUGHT_DIR } from '../core/paths.mjs';
11
+ import { DSH_HOME, THOUGHT_DIR } from '../core/paths.mjs';
12
12
  import { sessionKey } from '../core/keys.mjs';
13
13
  import { tg } from '../chat/telegram.mjs';
14
14
  import { topicName } from '../chat/topics.mjs';
@@ -16,7 +16,7 @@ import { t } from '../core/i18n.mjs';
16
16
  import { addStep, isSubagentTool, progressPanel, stepLine, subagentStep } from '../chat/panel.mjs';
17
17
  import { reasoningMode, thoughtRows } from '../chat/notes.mjs';
18
18
  import { cardBlocks } from './card.mjs';
19
- import { FILES_CAP, fileKeyboard, turnFiles } from './files.mjs';
19
+ import { FILES_CAP, finalKeyboard, turnFiles } from './files.mjs';
20
20
  import { cardPin } from '../profile/settings-card.mjs';
21
21
  import { continueKeyboard, errorKeyboard } from '../chat/keyboards.mjs';
22
22
  import { contextFill, contextRow, contextUsed } from './context-meter.mjs';
@@ -232,16 +232,18 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
232
232
  };
233
233
 
234
234
  /** The attachment keys for the final card, and the rows kept for the press. */
235
- const attachKeyboard = () => {
236
- const files = turnFiles(wroteCalls);
237
- if (!files.length) return [];
238
- // Stored per topic because the callback can only carry a number — a path
239
- // does not fit in 64 bytes. Storing them also makes a press on an older card
240
- // answer "stale" rather than sending whatever now sits at that index.
241
- state.turnFiles = { ...(state.turnFiles || {}), [panelKey]: files };
242
- saveStateNow();
243
- return fileKeyboard(files, lang, t);
244
- };
235
+ const attachKeyboard = () => finalKeyboard({
236
+ calls: wroteCalls,
237
+ state,
238
+ key: panelKey,
239
+ save: saveStateNow,
240
+ lang,
241
+ t,
242
+ // The ↻ row names the turn that just finished, read from the session it
243
+ // wrote — the file is hot in the page cache seconds after the turn.
244
+ sessionId: state.sessions?.[panelKey] || '',
245
+ sessionsRoot: join(DSH_HOME, 'sessions'),
246
+ });
245
247
 
246
248
  /** Send or edit the panel; `plainText` and a rejected parse fall back to text. */
247
249
  const post = async (method, payload, view, keyboard = undefined) => {
package/work/regen.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // Regenerate the last answer: the desktop's most-used button, one tap here.
2
+ //
3
+ // A retry that matters is two moves in one — the finished exchange must leave
4
+ // the session (a copy of it must not sit above the same question asked again),
5
+ // and the question itself is fed back as a fresh message. `/regen` is the one
6
+ // implementation of that; the ↻ button on a turn's final card only checks that
7
+ // the card still describes the last turn, then types the command.
8
+ import { recentTurns } from './rewind.mjs';
9
+
10
+ /** Callback data the ↻ button carries: `rg:<turn>:<last 8 of session id>`. */
11
+ export const REGEN_CALLBACK = /^rg:(\d{1,6}):([0-9a-f]{8})$/;
12
+
13
+ export function isRegenPress(data) {
14
+ return String(data || '').startsWith('rg:');
15
+ }
16
+
17
+ /**
18
+ * Whether a press still describes the last turn of the topic's session.
19
+ *
20
+ * Everything is re-read at press time: the tail catches a topic that moved to
21
+ * another session (branched, switched, fresh), and the turn number catches the
22
+ * one case a number-less button would get wrong — an older card of the same
23
+ * session, which would otherwise cut the CURRENT last turn while the person
24
+ * asked to redo the one the card was drawn for. Both answer `stale`.
25
+ *
26
+ * @returns {{ verdict: 'ok', turn: number, user: string } | { verdict: 'busy' | 'stale' }}
27
+ */
28
+ export function regenPressState(data, { sessionId = '', busy = false, file = '' } = {}) {
29
+ const match = REGEN_CALLBACK.exec(String(data || ''));
30
+ if (!match) return { verdict: 'stale' };
31
+ const [, turn, tail] = match;
32
+ if (!sessionId || !sessionId.endsWith(tail)) return { verdict: 'stale' };
33
+ if (busy) return { verdict: 'busy' };
34
+ const last = recentTurns(file, { limit: 1 })[0];
35
+ if (!last || Number(turn) !== last.turn) return { verdict: 'stale' };
36
+ return { verdict: 'ok', turn: last.turn, user: String(last.user || '') };
37
+ }
38
+
39
+ /**
40
+ * The ↻ row for a finished turn's card, first row above any file buttons.
41
+ *
42
+ * The turn number is read from the session at card time, so the button names
43
+ * the turn the card belongs to; a session that cannot be read gets no button —
44
+ * a ↻ that guesses would cut a turn it never saw.
45
+ */
46
+ export function regenRow(sessionId, file, lang, t) {
47
+ if (!sessionId || !file) return [];
48
+ const last = recentTurns(file, { limit: 1 })[0];
49
+ if (!last) return [];
50
+ return [{
51
+ text: `↻ ${t(lang, 'btn.regen')}`.slice(0, 64),
52
+ callback_data: `rg:${last.turn}:${sessionId.slice(-8)}`,
53
+ }];
54
+ }