dsh-composer-plus 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -37,9 +37,13 @@ export const HISTORY_PATH = '/api/composer-plus.idea-history';
37
37
  export const CONTENT_SEARCH_PATH = '/api/composer-plus.content-search';
38
38
  export const ROLLBACK_PATH = '/api/composer-plus.rollback';
39
39
  export const DELETE_CHAT_PATH = '/api/composer-plus.delete-chat';
40
+ export const QUEUE_MOVE_PATH = '/api/composer-plus.queue-move';
41
+ export const PREDICT_PATH = '/api/composer-plus.predict';
42
+ export const COMPLETE_PATH = '/api/composer-plus.complete';
43
+ export const EXPORT_PATH = '/api/composer-plus.export';
40
44
  /** Feature screenshots shipped in assets/features/<id>.webp; only these ids are served (no path input). */
41
45
  export const SHOTS = ['changesPanel', 'featureIdeas', 'projectStatus', 'recentProjects', 'collapseProjects', 'statusOrder', 'notifications', 'allowForChat', 'continueButton', 'resumeAfterRestart', 'inputHistory', 'planToggle', 'keepFocus',
42
- 'queueReorder', 'mobileConnect', 'copyDeeplink', 'copyProjectPath', 'language', 'autoUpdate', 'contentSearch', 'turnRollback', 'deleteChat', 'projectName'];
46
+ 'queueReorder', 'mobileConnect', 'copyDeeplink', 'copyProjectPath', 'projectPicker', 'nextPrediction', 'typingCompletion', 'exportMarkdown', 'language', 'autoUpdate', 'contentSearch', 'turnRollback', 'deleteChat', 'projectName'];
43
47
  const PACKAGE = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
44
48
  const NPM_NAME = 'dsh-composer-plus';
45
49
  const RELEASES_URL = 'https://api.github.com/repos/furkancak1r/dsh-composer-plus/releases/latest';
@@ -356,6 +360,20 @@ export function resumeTracker({ store, isRoot, running = () => [], wakeOne, log
356
360
  };
357
361
  }
358
362
 
363
+ /** Wake an idle chat with the hidden Continue step, and leave the user's queued messages for later turns (issue #3).
364
+ * ponytail: dsh opens a turn by claiming every next-step message plus the queue head in one batch, so a steer marker alone
365
+ * also took the first queued message. A second marker at the queue head is claimed in its place; the pre-step hook keeps
366
+ * one note. Upgrade when dsh can start a turn without the queue head. A dsh without `inbox.prepend` gets the steer only. */
367
+ function wakeWithContinue(agent) {
368
+ const marker = () => ({ id: randomUUID(), role: 'user', content: [], source: { kind: CONTINUE_SOURCE } });
369
+ const head = typeof agent.inbox?.prepend === 'function' ? marker() : undefined;
370
+ if (head !== undefined) agent.inbox.prepend('next-turn', head);
371
+ try { agent.steer(marker()); } catch (error) {
372
+ if (head !== undefined) agent.inbox.remove(head.id); // no empty row stays in the queue
373
+ throw error;
374
+ }
375
+ }
376
+
359
377
  /** Continue one chat after a restart, if dsh (not the user) stopped its last turn: the chat gets the same hidden "continue"
360
378
  * step as One-click Continue. When the stopped turn was a goal round, the goal is armed again instead (dsh disarms goals at
361
379
  * every start and waits for `/goal resume`), and dsh's goal driver starts the next round, so the model can still mark the
@@ -382,7 +400,7 @@ export async function wakeSession({ sessionController, sessionQuery, goals, arch
382
400
  if (goal !== undefined && ((goal.phase === 'active' && goal.activation !== 'armed') || (goal.phase === 'paused' && goal.updatedAt >= start.time))) {
383
401
  try { goals.resume(agent, { id: goal.id, revision: goal.revision }); return 'goal'; } catch { /* no goal rounds left: continue the turn */ }
384
402
  }
385
- agent.steer({ id: randomUUID(), role: 'user', content: [], source: { kind: CONTINUE_SOURCE } });
403
+ wakeWithContinue(agent);
386
404
  return 'continued';
387
405
  }
388
406
 
@@ -457,6 +475,14 @@ export function ideasLanguage(locale) {
457
475
  }
458
476
 
459
477
  const clip = (value, max) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '');
478
+ /** Feature ideas: the longest focus topic that the user can give. */
479
+ export const FOCUS_MAX = 80;
480
+ /** The focus line of the idea prompt: the user's topic (one line, at most FOCUS_MAX characters, JSON-quoted so it stays one
481
+ * quoted value), or '' without a topic, so the prompt stays the same as before. */
482
+ export function ideasFocus(focus) {
483
+ const topic = clip(focus, FOCUS_MAX);
484
+ return topic === '' ? '' : `\n\nFocus topic chosen by the user: ${JSON.stringify(topic)}. Suggest only features about this topic.`;
485
+ }
460
486
  /** One idea, cleaned and bounded (from the model or the browser), or undefined without a title and a summary. */
461
487
  const ideaFrom = (item) => {
462
488
  const title = clip(item?.title, 120);
@@ -523,10 +549,11 @@ export function ideaHistory(store) {
523
549
  };
524
550
  }
525
551
 
526
- /** One model call for feature ideas about the chat's project, written in `locale` (the dsh UI language) when given.
527
- * `avoid(cwd)` names the earlier ideas (history and the Later list): the model is told to skip them, and a repeated title
528
- * is dropped. `record(cwd, ideas)` keeps the new ones. Read-only for the project: no chat message, nothing written there. */
529
- export async function suggestIdeas({ llm, sessionQuery, subprocess, defaultModel, avoid, record }, sessionId, signal, locale) {
552
+ /** One model call for feature ideas about the chat's project, written in `locale` (the dsh UI language) when given and
553
+ * limited to `focus` (the user's topic) when given. `avoid(cwd)` names the earlier ideas (history and the Later list): the
554
+ * model is told to skip them, and a repeated title is dropped. `record(cwd, ideas)` keeps the new ones. Read-only for the
555
+ * project: no chat message, nothing written there. */
556
+ export async function suggestIdeas({ llm, sessionQuery, subprocess, defaultModel, avoid, record }, sessionId, signal, locale, focus) {
530
557
  const observation = await sessionQuery.observeSession(sessionId, { signal, projectionMode: 'none' });
531
558
  let cwd, route;
532
559
  try { cwd = observation.header?.cwd; route = ideasRoute(observation.events ?? [], defaultModel); } finally { observation[Symbol.dispose]?.(); }
@@ -550,7 +577,7 @@ export async function suggestIdeas({ llm, sessionQuery, subprocess, defaultModel
550
577
  let text = '';
551
578
  let finish;
552
579
  for await (const chunk of call.stream({ ...call.config, system: `${IDEAS_SYSTEM}\n${ideasLanguage(locale)}`, signal: callSignal,
553
- messages: [{ role: 'user', content: [{ type: 'text', text: `Project folder name: ${cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? ''}\n\n${brief}${asked}` }] }] })) {
580
+ messages: [{ role: 'user', content: [{ type: 'text', text: `Project folder name: ${cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? ''}\n\n${brief}${asked}${ideasFocus(focus)}` }] }] })) {
554
581
  if (chunk.type === 'text-delta') text += chunk.text;
555
582
  else if (chunk.type === 'finish') finish = chunk.reason;
556
583
  }
@@ -676,8 +703,11 @@ export function rollbackPlan(surface, seq) {
676
703
  }
677
704
  export const rollbackMarker = () => Object.freeze({ id: randomUUID(), role: 'user', content: Object.freeze([Object.freeze({ type: 'text', text: ROLLBACK_TEXT })]),
678
705
  source: Object.freeze({ kind: ROLLBACK_SOURCE }) });
679
- /** The spans a chat's markers hide in the view, as `[first withdrawn seq, marker seq]`. */
680
- export const rollbackSpans = (events) => events.filter((e) => e.type === 'user/message' && e.data?.source?.kind === ROLLBACK_SOURCE && Array.isArray(e.sourceEventSeqs) && e.sourceEventSeqs.length > 0)
706
+ /** The marker kind of dsh-rewind-plugin: the same shape as ours (it withdraws `sourceEventSeqs`). */
707
+ export const REWIND_SOURCE = 'dsh-rewind';
708
+ /** The spans that the markers of `kinds` hide, as `[first withdrawn seq, marker seq]`. By default only ours: the ↶ view
709
+ * hides those, and dsh-rewind-plugin hides its own. dsh's /compact marker is not a withdraw: never pass its kind. */
710
+ export const rollbackSpans = (events, kinds = [ROLLBACK_SOURCE]) => events.filter((e) => e.type === 'user/message' && kinds.includes(e.data?.source?.kind) && Array.isArray(e.sourceEventSeqs) && e.sourceEventSeqs.length > 0)
681
711
  .map((e) => [Math.min(...e.sourceEventSeqs), e.seq]);
682
712
 
683
713
  /** `path` relative to `root` ('' for root itself, '/' separators), or undefined when it is outside. Both are real paths. */
@@ -933,10 +963,12 @@ export function apply(ctx) {
933
963
  // The empty wake marker opens the step; it is then replaced by a fresh context message. Only messages
934
964
  // claimed from the inbox render as a chat bubble, so the replacement stays out of Chat, but it gives the
935
965
  // model a final user turn: providers such as Claude reject a request that ends on an assistant message.
966
+ // A wake claims two markers (see wakeWithContinue): the model gets one note, at the first marker's place.
936
967
  ctx.on('agent/pre-step', async (payload, next) => {
937
968
  const decision = await next();
938
969
  if (decision.kind !== 'enter' || !decision.messages.some((m) => m.source?.kind === CONTINUE_SOURCE)) return decision;
939
- return { ...decision, messages: decision.messages.map((m) => (m.source?.kind === CONTINUE_SOURCE ? continueMessage() : m)) };
970
+ const first = decision.messages.findIndex((m) => m.source?.kind === CONTINUE_SOURCE);
971
+ return { ...decision, messages: decision.messages.flatMap((m, i) => (m.source?.kind !== CONTINUE_SOURCE ? [m] : i === first ? [continueMessage()] : [])) };
940
972
  }, true);
941
973
  ctx.connection.fetch.register({
942
974
  path: CONTINUE_PATH, methods: ['POST'], requestBody: 'buffered',
@@ -955,7 +987,7 @@ export function apply(ctx) {
955
987
  return json({ error: 'session no longer needs continuation' }, 409);
956
988
  }
957
989
  request.signal.throwIfAborted();
958
- agent.steer({ id: randomUUID(), role: 'user', content: [], source: { kind: CONTINUE_SOURCE } });
990
+ wakeWithContinue(agent);
959
991
  return json({ accepted: true });
960
992
  } finally { observation[Symbol.dispose]?.(); }
961
993
  } catch { return json({ error: 'continuation failed' }, 500); }
@@ -1082,6 +1114,62 @@ export function apply(ctx) {
1082
1114
  const snapshots = snapshotStore({ subprocess: ctx.subprocess, dir: join(home, 'cache', 'composer-plus', 'rollback') });
1083
1115
  installRollback(ctx, home, snapshots);
1084
1116
  installDeleteChat(ctx, home, snapshots);
1117
+ installQueueMove(ctx);
1118
+ installPredict(ctx, home);
1119
+ installComplete(ctx, home);
1120
+ installExport(ctx);
1121
+ }
1122
+
1123
+ /** Queue drag-and-drop (Host half): `POST {sessionId, itemId, to, before}` moves one queued next-turn message to index `to`
1124
+ * of `before`, with its images and files, in dsh's own inbox (the message keeps its id). dsh's queue `edit`
1125
+ * takes text only, so moving text between rows cannot move a message with an attachment. `before` (the ids the user
1126
+ * saw, in order) must still be the queue: a message that started to send meanwhile makes it 409, and nothing moves. */
1127
+ function installQueueMove(ctx) {
1128
+ const busy = new Set();
1129
+ ctx.connection.fetch.register({
1130
+ path: QUEUE_MOVE_PATH, methods: ['POST'], requestBody: 'buffered',
1131
+ fetch: async (request) => {
1132
+ let body;
1133
+ try { body = await request.json(); } catch { return json({ error: 'bad request' }, 400); }
1134
+ const { sessionId, itemId, to, before } = body ?? {};
1135
+ if (!isText(sessionId) || !isText(itemId) || !Number.isSafeInteger(to) || to < 0 || !Array.isArray(before) || !before.every((id) => isText(id))) return json({ error: 'bad request' }, 400);
1136
+ if (busy.has(sessionId)) return json({ error: 'a move in this chat is already running' }, 409);
1137
+ busy.add(sessionId);
1138
+ try {
1139
+ const found = await ctx.sessionController.resolveAgent(sessionId);
1140
+ if ('error' in found) return json({ error: 'this chat is not available' }, 409);
1141
+ const { agent } = found;
1142
+ const inbox = agent.inbox;
1143
+ if (inbox?.splice === undefined || !Array.isArray(inbox.nextTurn)) return json({ error: 'this dsh cannot move queued messages' }, 409);
1144
+ if (!isRootChat(agent.session)) {
1145
+ const sub = ctx.sessionProjections?.snapshot?.(agent.session, ['subagent'])?.values?.subagent;
1146
+ if (sub?.mode !== 'continuable') return json({ error: 'this chat cannot change its queue' }, 409);
1147
+ }
1148
+ const queue = inbox.nextTurn;
1149
+ const ids = queue.map((m) => m.id);
1150
+ // Only the rows the user saw may move: dsh hides the ones already echoed in the chat, so `before` can be a
1151
+ // part of the queue, in the same order.
1152
+ const seen = ids.filter((id) => before.includes(id));
1153
+ if (seen.length !== before.length || seen.some((id, i) => id !== before[i]) || !before.includes(itemId) || to >= before.length) {
1154
+ return json({ error: 'the queue changed; a message may have already started sending' }, 409);
1155
+ }
1156
+ const from = ids.indexOf(itemId);
1157
+ const target = ids.indexOf(before[to]);
1158
+ if (from === target) return json({ moved: false });
1159
+ // One splice over the rows between the two places, in their new order: one log event, the same ids. dsh logs
1160
+ // it as "canceled + inserted", which its chat view and its turn bookkeeping do not count as a claim. Only your
1161
+ // own messages move: a goal round or a question reply in that range has its own listeners on a removal.
1162
+ const lo = Math.min(from, target), hi = Math.max(from, target);
1163
+ const range = queue.slice(lo, hi + 1);
1164
+ if (!range.every((m) => m.source?.kind === 'user')) return json({ error: 'only your own queued messages can move' }, 409);
1165
+ const order = [...range];
1166
+ order.splice(target - lo, 0, order.splice(from - lo, 1)[0]);
1167
+ inbox.splice('next-turn', lo, range.length, order);
1168
+ return json({ moved: true, order: inbox.nextTurn.map((m) => m.id) });
1169
+ } catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
1170
+ finally { busy.delete(sessionId); }
1171
+ },
1172
+ });
1085
1173
  }
1086
1174
 
1087
1175
  /** Wait until the agent is idle, at most `ms`; false on time-out. */
@@ -1261,8 +1349,8 @@ function installContentSearch(ctx, home) {
1261
1349
  });
1262
1350
  }
1263
1351
 
1264
- /** Feature ideas: `POST {sessionId, locale?}` asks the chat's model for ideas (never one from the project's history or
1265
- * Later list); `POST {sessionId, idea}` starts a chat for one idea.
1352
+ /** Feature ideas: `POST {sessionId, locale?, focus?}` asks the chat's model for ideas (never one from the project's history
1353
+ * or Later list; only about `focus` when it has text); `POST {sessionId, idea}` starts a chat for one idea.
1266
1354
  * Ideas saved for later: `GET ?sessionId` lists the project's ideas; `POST {sessionId, add | remove | start | startAll}`
1267
1355
  * changes the list (`start` starts a chat for the stored idea and removes it once the chat runs).
1268
1356
  * Idea history: `GET ?sessionId` lists the project's earlier ideas; `POST {sessionId, remove | clear}` forgets one or all.
@@ -1298,7 +1386,7 @@ function installIdeas(ctx, home) {
1298
1386
  // Not again: every earlier suggestion of this project (skipped, started, saved) and the Later list.
1299
1387
  const avoid = async (cwd) => [...(await titles(history, cwd)), ...(await titles(later, cwd))];
1300
1388
  return json(await suggestIdeas({ llm, sessionQuery: ctx.sessionQuery, subprocess: ctx.subprocess, defaultModel: get('agentDefaultModel'), avoid, record: history.record },
1301
- body.sessionId, request.signal, body.locale));
1389
+ body.sessionId, request.signal, body.locale, body.focus));
1302
1390
  } catch (error) { return json({ error: String(error?.message ?? error) }, status(error)); }
1303
1391
  },
1304
1392
  });
@@ -1399,3 +1487,403 @@ function installResume(ctx, home) {
1399
1487
  },
1400
1488
  });
1401
1489
  }
1490
+
1491
+ /** Next message prediction: after a turn ends, a guess of the user's next message in the same chat (Codex "composer
1492
+ * predictions"). On by default (the owner's choice): one short model call per finished turn, no chat turn and nothing in
1493
+ * the chat. The Host keeps the switch and the model choice in `predict.json`. The model is dsh's default unless the user picked another one from dsh's own
1494
+ * model catalog. Nothing goes into the chat: the browser shows the text and Tab puts it in the composer. */
1495
+ export const PREDICT_TIMEOUT_MS = 45000;
1496
+ export const PREDICT_MAX_TOKENS = 4000;
1497
+ const PREDICT_MAX = 300; // characters of one prediction
1498
+ const PREDICT_CONTEXT = 6000; // characters of chat the model reads
1499
+ const PREDICT_SYSTEM = `You predict the next message that the user will type in a chat with an AI coding agent.
1500
+ Read the recent conversation. Write the single most likely next message from the user, as the user would type it: short (one sentence, at most 25 words), in the user's own language and tone, and specific to this conversation. Typical next messages ask for the obvious next step, ask to check or test the result, or ask a follow-up question.
1501
+ Answer with the message text only: no quotes, no label, no explanation. If no next message is likely, answer with nothing.`;
1502
+
1503
+ /** Saved settings: `{on, model?: {provider, model}}`. No file or a broken file reads as on with dsh's default model; only
1504
+ * a saved `on: false` (the user's switch) turns it off. */
1505
+ export function predictStore(file) {
1506
+ const read = async () => {
1507
+ try {
1508
+ const v = JSON.parse(await readFile(file, 'utf8'));
1509
+ const model = isText(v?.model?.provider) && isText(v?.model?.model) ? { provider: v.model.provider, model: v.model.model } : undefined;
1510
+ return { on: v?.on !== false, ...(model === undefined ? {} : { model }) };
1511
+ } catch { return { on: true }; }
1512
+ };
1513
+ let queue = Promise.resolve(); // one write at a time: they share a temp file name and merge into the newest state
1514
+ const change = (mutate) => {
1515
+ const done = queue.then(async () => {
1516
+ const next = mutate(await read());
1517
+ await mkdir(dirname(file), { recursive: true });
1518
+ const tmp = `${file}.${process.pid}.tmp`;
1519
+ await writeFile(tmp, JSON.stringify(next), { mode: 0o600 });
1520
+ await rename(tmp, file);
1521
+ return next;
1522
+ });
1523
+ queue = done.catch(() => {});
1524
+ return done;
1525
+ };
1526
+ return { read, change };
1527
+ }
1528
+
1529
+ /** Text blocks of a message content, joined. */
1530
+ const textBlocks = (content) => (Array.isArray(content) ? content.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('') : '');
1531
+ /** The recent conversation for the prediction: the user's own messages and the agent's replies (no tools, no hidden
1532
+ * context), oldest first, the newest kept when it is long. `undefined` when the chat has no reply after its last message. */
1533
+ export function predictTranscript(events) {
1534
+ const lines = [];
1535
+ for (const e of events) {
1536
+ if (e.type === 'user/message' && e.data?.source?.kind === 'user') {
1537
+ const text = textBlocks(e.data.content).trim();
1538
+ if (text !== '') lines.push({ who: 'User', text });
1539
+ } else if (e.type === 'assistant/message') {
1540
+ const text = textBlocks(e.data?.message?.content).trim();
1541
+ if (text !== '') lines.push({ who: 'Agent', text });
1542
+ }
1543
+ }
1544
+ if (lines.at(-1)?.who !== 'Agent') return undefined;
1545
+ const out = [];
1546
+ let size = 0;
1547
+ for (let i = lines.length - 1; i >= 0 && size < PREDICT_CONTEXT; i--) {
1548
+ const room = PREDICT_CONTEXT - size;
1549
+ const text = lines[i].text.length > room ? `…${lines[i].text.slice(-room)}` : lines[i].text;
1550
+ out.unshift(`${lines[i].who}: ${text}`);
1551
+ size += text.length;
1552
+ }
1553
+ return out.join('\n\n');
1554
+ }
1555
+ /** The model's answer as one clean line: no quotes or label; empty when it has nothing useful. */
1556
+ export function cleanPrediction(text) {
1557
+ let line = String(text ?? '').replace(/<think>[\s\S]*?<\/think>/g, '').trim().split(/\r?\n/).find((l) => l.trim() !== '') ?? '';
1558
+ line = line.trim().replace(/^(user|next message|message)\s*:\s*/i, '').replace(/^["'“”‘’`]+|["'“”‘’`]+$/g, '').trim();
1559
+ return line.length > PREDICT_MAX ? `${line.slice(0, PREDICT_MAX - 1).trimEnd()}…` : line;
1560
+ }
1561
+
1562
+ /** The newest `turn/end`, when it is the last turn event of the chat and the turn finished normally. */
1563
+ export function finishedTurn(events) {
1564
+ const last = events.findLast((e) => e.type === 'turn/start' || e.type === 'turn/end');
1565
+ return last?.type === 'turn/end' && last.data?.reason?.kind === 'completed' ? last.seq : undefined;
1566
+ }
1567
+
1568
+ /** dsh's model list with the deployment default, the same data as dsh's own model menu. */
1569
+ async function modelCatalogOf(ctx, get) {
1570
+ const llm = get('llm');
1571
+ const fallback = get('agentDefaultModel')?.currentSelection?.();
1572
+ const out = { default: isText(fallback?.provider) && isText(fallback?.model) ? { provider: fallback.provider, model: fallback.model } : undefined, groups: [] };
1573
+ if (llm?.listProviders === undefined) return out;
1574
+ for (const provider of llm.listProviders()) {
1575
+ try {
1576
+ const models = (await llm.listModels(provider.id)).map((m) => ({ id: m.id, name: m.name }));
1577
+ if (models.length > 0) out.groups.push({ id: provider.id, name: provider.name ?? provider.id, models });
1578
+ } catch { /* a provider that cannot list its models is left out, as in dsh's own menu */ }
1579
+ }
1580
+ return out;
1581
+ }
1582
+
1583
+ /** The model for a prediction or a completion: the first saved one that dsh still lists, else dsh's default. */
1584
+ async function routeOf(ctx, get, ...saved) {
1585
+ const catalog = await modelCatalogOf(ctx, get);
1586
+ const listed = (m) => m !== undefined && catalog.groups.some((g) => g.id === m.provider && g.models.some((x) => x.id === m.model));
1587
+ return saved.find(listed) ?? catalog.default;
1588
+ }
1589
+
1590
+ /** One model call: the next user message of this chat, after the turn that ended at `afterSeq`. */
1591
+ export async function predictNext({ llm, sessionQuery, route }, sessionId, afterSeq, signal) {
1592
+ const observation = await sessionQuery.observeSession(sessionId, { signal, projectionMode: 'none' });
1593
+ let transcript, origin;
1594
+ try {
1595
+ const events = observation.events ?? [];
1596
+ origin = observation.header?.origin;
1597
+ if (finishedTurn(events) !== afterSeq) throw Object.assign(new Error('the chat moved on'), { status: 409 });
1598
+ transcript = predictTranscript(events);
1599
+ } finally { observation[Symbol.dispose]?.(); }
1600
+ if (origin === 'subagent') throw Object.assign(new Error('not for a subagent chat'), { status: 409 });
1601
+ if (transcript === undefined) return { text: '', afterSeq };
1602
+ const timeout = AbortSignal.timeout(PREDICT_TIMEOUT_MS);
1603
+ const callSignal = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
1604
+ const call = await llm.prepareCall(route, callSignal, (controls, model) => {
1605
+ // The lowest reasoning effort keeps it fast; the output cap never goes above the model's own default.
1606
+ const first = model?.reasoning?.efforts?.[0];
1607
+ const cap = Number.isSafeInteger(model?.defaultMaxTokens) && model.defaultMaxTokens > 0 ? Math.min(PREDICT_MAX_TOKENS, model.defaultMaxTokens) : PREDICT_MAX_TOKENS;
1608
+ return { ...controls, maxTokens: cap, ...(first === undefined ? {} : { reasoningEffort: first.id }) };
1609
+ });
1610
+ let text = '';
1611
+ let finish;
1612
+ for await (const chunk of call.stream({ ...call.config, system: PREDICT_SYSTEM, signal: callSignal,
1613
+ messages: [{ role: 'user', content: [{ type: 'text', text: `Recent conversation:\n\n${transcript}\n\nThe user's next message:` }] }] })) {
1614
+ if (chunk.type === 'text-delta') text += chunk.text;
1615
+ else if (chunk.type === 'finish') finish = chunk.reason;
1616
+ }
1617
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message || `the model call ended: ${finish.kind}`);
1618
+ return { text: cleanPrediction(text), afterSeq, model: route.model };
1619
+ }
1620
+
1621
+ function installPredict(ctx, home) {
1622
+ const get = (name) => { try { return ctx.get?.(name); } catch { return undefined; } };
1623
+ const store = predictStore(join(home, 'storages', 'dsh-composer-plus', 'predict.json'));
1624
+ const running = new Map(); // sessionId → { afterSeq, promise }: one call per chat; the same turn shares it
1625
+ // sessionId → { key, result }: the last answer per chat, so a reopened chat, a second tab or the phone costs no new call.
1626
+ // A new turn or another model makes a new key. ponytail: at most PREDICT_CACHE chats, the oldest go first.
1627
+ const done = new Map();
1628
+ const PREDICT_CACHE = 200;
1629
+ const routeFor = (saved) => routeOf(ctx, get, saved);
1630
+ ctx.connection.fetch.register({
1631
+ path: PREDICT_PATH, methods: ['GET', 'POST'], requestBody: 'buffered',
1632
+ fetch: async (request) => {
1633
+ if (request.method === 'GET') {
1634
+ const settings = await store.read();
1635
+ if (new URL(request.url).searchParams.get('catalog') === '1') return json({ ...settings, catalog: await modelCatalogOf(ctx, get) });
1636
+ return json(settings);
1637
+ }
1638
+ let body;
1639
+ try { body = await request.json(); } catch { return json({ error: 'bad request' }, 400); }
1640
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return json({ error: 'bad request' }, 400);
1641
+ if (typeof body.on === 'boolean' && body.sessionId === undefined && body.model === undefined) {
1642
+ try { return json(await store.change((v) => ({ ...v, on: body.on }))); } catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
1643
+ }
1644
+ // null: back to dsh's default.
1645
+ if (body.model !== undefined && body.sessionId === undefined && body.on === undefined) return saveModel(ctx, get, store, body.model);
1646
+ if (!isText(body.sessionId) || !Number.isSafeInteger(body.afterSeq) || body.afterSeq < 0 || body.on !== undefined || body.model !== undefined) return json({ error: 'bad request' }, 400);
1647
+ const settings = await store.read();
1648
+ if (!settings.on) return json({ error: 'next message prediction is off' }, 409);
1649
+ const llm = get('llm');
1650
+ if (llm?.prepareCall === undefined) return json({ error: 'this dsh profile cannot call a model' }, 409);
1651
+ const route = await routeFor(settings.model);
1652
+ if (route === undefined) return json({ error: 'no model is selected' }, 409);
1653
+ const key = JSON.stringify([body.afterSeq, route.provider, route.model]);
1654
+ const kept = done.get(body.sessionId);
1655
+ if (kept?.key === key) {
1656
+ // Only while that turn is still the chat's last one (a newer turn makes the guess stale).
1657
+ let fresh = false;
1658
+ try {
1659
+ const observation = await ctx.sessionQuery.observeSession(body.sessionId, { signal: request.signal, projectionMode: 'none' });
1660
+ try { fresh = observation.header?.origin !== 'subagent' && finishedTurn(observation.events ?? []) === body.afterSeq; } finally { observation[Symbol.dispose]?.(); }
1661
+ } catch { fresh = false; }
1662
+ if (!fresh) return json({ error: 'the chat moved on' }, 409);
1663
+ return json(kept.result);
1664
+ }
1665
+ const same = running.get(body.sessionId);
1666
+ if (same !== undefined && same.afterSeq === body.afterSeq) {
1667
+ try { return json(await same.promise); } catch (error) { return json({ error: String(error?.message ?? error) }, Number.isInteger(error?.status) ? error.status : 502); }
1668
+ }
1669
+ if (same !== undefined) return json({ error: 'a prediction for this chat is still running' }, 409);
1670
+ // Shared by every request for this turn (two tabs, the phone): no request's signal may cancel it. The call has its own
1671
+ // timeout, so it always ends.
1672
+ const promise = predictNext({ llm, sessionQuery: ctx.sessionQuery, route }, body.sessionId, body.afterSeq).then((result) => {
1673
+ done.delete(body.sessionId);
1674
+ done.set(body.sessionId, { key, result });
1675
+ if (done.size > PREDICT_CACHE) done.delete(done.keys().next().value);
1676
+ return result;
1677
+ });
1678
+ running.set(body.sessionId, { afterSeq: body.afterSeq, promise });
1679
+ try { return json(await promise); }
1680
+ catch (error) { return json({ error: String(error?.message ?? error) }, Number.isInteger(error?.status) ? error.status : 502); }
1681
+ finally { if (running.get(body.sessionId)?.promise === promise) running.delete(body.sessionId); }
1682
+ },
1683
+ });
1684
+ }
1685
+
1686
+ /** Complete while typing (Host half): the rest of the message the user is typing now. Its model is its own choice, else
1687
+ * the next message prediction's model, else dsh's default. Off by default: it makes a model call at each pause while the
1688
+ * user types. The Host keeps the switch and the model in `complete.json`. Nothing goes into the chat: the browser shows the
1689
+ * text and Tab adds it to the composer. */
1690
+ export const COMPLETE_TIMEOUT_MS = 15000;
1691
+ export const COMPLETE_MAX_TOKENS = 2000;
1692
+ const COMPLETE_MAX = 150; // characters of one completion
1693
+ const COMPLETE_INPUT = 4000; // characters of typed text the route accepts
1694
+ const COMPLETE_CONTEXT = 3000; // characters of chat the model reads
1695
+ const COMPLETE_SYSTEM = `You complete the message that the user is typing in a chat with an AI coding agent.
1696
+ You get the recent conversation (it can be empty) and the text that the user typed so far. Write only the words that come next, so that the typed text plus your words is one natural message in the user's own language and tone. Keep it short: end the current sentence, at most 15 words.
1697
+ Start exactly where the typed text stops: if it stops in the middle of a word, start with the rest of that word; if it ends with a space, start with the next word. Do not repeat the typed text. Answer with the new words only: no quotes, no label, no explanation. If you cannot continue it well, answer with nothing.`;
1698
+
1699
+ /** Saved settings: `{on, model?: {provider, model}}`. No file or a broken file reads as off with no own model; only a saved
1700
+ * `on: true` (the user's switch) turns it on. No `model`: the prediction's model is used. */
1701
+ export function completeStore(file) {
1702
+ const read = async () => {
1703
+ try {
1704
+ const v = JSON.parse(await readFile(file, 'utf8'));
1705
+ const model = isText(v?.model?.provider) && isText(v?.model?.model) ? { provider: v.model.provider, model: v.model.model } : undefined;
1706
+ return { on: v?.on === true, ...(model === undefined ? {} : { model }) };
1707
+ } catch { return { on: false }; }
1708
+ };
1709
+ let queue = Promise.resolve(); // one write at a time: they share a temp file name and merge into the newest state
1710
+ const change = (mutate) => {
1711
+ const done = queue.then(async () => {
1712
+ const next = mutate(await read());
1713
+ await mkdir(dirname(file), { recursive: true });
1714
+ const tmp = `${file}.${process.pid}.tmp`;
1715
+ await writeFile(tmp, JSON.stringify(next), { mode: 0o600 });
1716
+ await rename(tmp, file);
1717
+ return next;
1718
+ });
1719
+ queue = done.catch(() => {});
1720
+ return done;
1721
+ };
1722
+ return { read, change };
1723
+ }
1724
+ /** `POST {model}` on a settings route: `null` removes the saved model; a model must be one that dsh lists now. Answers
1725
+ * the saved settings. Shared by Next message prediction and Complete while typing. */
1726
+ async function saveModel(ctx, get, store, model) {
1727
+ let chosen;
1728
+ if (model !== null) {
1729
+ if (!isText(model?.provider) || !isText(model?.model)) return json({ error: 'bad request' }, 400);
1730
+ const catalog = await modelCatalogOf(ctx, get);
1731
+ if (!catalog.groups.some((g) => g.id === model.provider && g.models.some((m) => m.id === model.model))) return json({ error: 'dsh does not list this model' }, 409);
1732
+ chosen = { provider: model.provider, model: model.model };
1733
+ }
1734
+ try { return json(await store.change(({ model: _, ...v }) => (chosen === undefined ? v : { ...v, model: chosen }))); }
1735
+ catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
1736
+ }
1737
+
1738
+ /** The chat for a completion: the user's messages and the agent's replies, newest kept; '' for a new chat. */
1739
+ export function completeContext(events) {
1740
+ const lines = [];
1741
+ for (const e of events) {
1742
+ if (e.type === 'user/message' && e.data?.source?.kind === 'user') {
1743
+ const text = textBlocks(e.data.content).trim();
1744
+ if (text !== '') lines.push(`User: ${text}`);
1745
+ } else if (e.type === 'assistant/message') {
1746
+ const text = textBlocks(e.data?.message?.content).trim();
1747
+ if (text !== '') lines.push(`Agent: ${text}`);
1748
+ }
1749
+ }
1750
+ const all = lines.join('\n\n');
1751
+ return all.length > COMPLETE_CONTEXT ? `…${all.slice(-COMPLETE_CONTEXT)}` : all;
1752
+ }
1753
+
1754
+ /** The model's answer as the words that come after `typed`: one line, no repeat of the typed text, at most COMPLETE_MAX
1755
+ * characters (cut at a word end). The model's own leading space means "a new word"; without one it ends the typed word. */
1756
+ export function cleanCompletion(typed, raw) {
1757
+ let line = String(raw ?? '').replace(/<think>[\s\S]*?<\/think>/g, '').split(/\r?\n/).find((l) => l.trim() !== '') ?? '';
1758
+ line = line.replace(/^\s*(completion|continuation|next words?)\s*:\s*/i, '');
1759
+ // Quotes around the whole answer go; a single leading apostrophe stays (Turkish "dsh" + "'yi").
1760
+ const bare = line.trim();
1761
+ if (bare.length >= 2 && /^["“`]/.test(bare) && /["”`]$/.test(bare)) line = (/^\s/.test(line) ? ' ' : '') + bare.slice(1, -1);
1762
+ // A model that writes the whole message again: keep only the new part.
1763
+ const head = typed.trimStart();
1764
+ if (head !== '' && line.trimStart().toLowerCase().startsWith(head.toLowerCase())) line = line.trimStart().slice(head.length);
1765
+ if (/\s$/.test(typed)) line = line.trimStart();
1766
+ line = line.replace(/\s+$/, '');
1767
+ if (line.trim() === '') return '';
1768
+ return line.length > COMPLETE_MAX ? line.slice(0, COMPLETE_MAX).replace(/\s+\S*$/, '') : line;
1769
+ }
1770
+
1771
+ /** One model call: the rest of `typed` for the chat `sessionId`. */
1772
+ export async function completeTyping({ llm, sessionQuery, route }, sessionId, typed, signal) {
1773
+ const observation = await sessionQuery.observeSession(sessionId, { signal, projectionMode: 'none' });
1774
+ let context, origin;
1775
+ try { origin = observation.header?.origin; context = completeContext(observation.events ?? []); } finally { observation[Symbol.dispose]?.(); }
1776
+ if (origin === 'subagent') throw Object.assign(new Error('not for a subagent chat'), { status: 409 });
1777
+ const timeout = AbortSignal.timeout(COMPLETE_TIMEOUT_MS);
1778
+ const callSignal = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
1779
+ const call = await llm.prepareCall(route, callSignal, (controls, model) => {
1780
+ const first = model?.reasoning?.efforts?.[0];
1781
+ const cap = Number.isSafeInteger(model?.defaultMaxTokens) && model.defaultMaxTokens > 0 ? Math.min(COMPLETE_MAX_TOKENS, model.defaultMaxTokens) : COMPLETE_MAX_TOKENS;
1782
+ return { ...controls, maxTokens: cap, ...(first === undefined ? {} : { reasoningEffort: first.id }) };
1783
+ });
1784
+ let text = '';
1785
+ let finish;
1786
+ const prompt = `${context === '' ? 'Recent conversation: (none, a new chat)' : `Recent conversation:\n\n${context}`}\n\nThe user typed so far (between the markers):\n<<<${typed}>>>\n\nThe words that come next:`;
1787
+ for await (const chunk of call.stream({ ...call.config, system: COMPLETE_SYSTEM, signal: callSignal, messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }] })) {
1788
+ if (chunk.type === 'text-delta') text += chunk.text;
1789
+ else if (chunk.type === 'finish') finish = chunk.reason;
1790
+ }
1791
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message || `the model call ended: ${finish.kind}`);
1792
+ return { text: typed, completion: cleanCompletion(typed, text), model: route.model };
1793
+ }
1794
+
1795
+ function installComplete(ctx, home) {
1796
+ const get = (name) => { try { return ctx.get?.(name); } catch { return undefined; } };
1797
+ const store = completeStore(join(home, 'storages', 'dsh-composer-plus', 'complete.json'));
1798
+ // Without its own model, the prediction's (Settings → Next message prediction → Model).
1799
+ const predict = predictStore(join(home, 'storages', 'dsh-composer-plus', 'predict.json'));
1800
+ const running = new Map(); // sessionId → AbortController: a newer request for the chat stops the older call
1801
+ ctx.connection.fetch.register({
1802
+ path: COMPLETE_PATH, methods: ['GET', 'POST'], requestBody: 'buffered',
1803
+ fetch: async (request) => {
1804
+ if (request.method === 'GET') {
1805
+ const settings = await store.read();
1806
+ // `catalog=1`: dsh's model list and the prediction's model, for the "Same as Next message prediction" entry.
1807
+ if (new URL(request.url).searchParams.get('catalog') === '1') return json({ ...settings, catalog: await modelCatalogOf(ctx, get), fallback: (await predict.read()).model ?? null });
1808
+ return json(settings);
1809
+ }
1810
+ let body;
1811
+ try { body = await request.json(); } catch { return json({ error: 'bad request' }, 400); }
1812
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return json({ error: 'bad request' }, 400);
1813
+ if (typeof body.on === 'boolean' && body.sessionId === undefined && body.text === undefined && body.model === undefined) {
1814
+ try { return json(await store.change((v) => ({ ...v, on: body.on }))); } catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
1815
+ }
1816
+ // null: back to the prediction's model.
1817
+ if (body.model !== undefined && body.sessionId === undefined && body.text === undefined && body.on === undefined) return saveModel(ctx, get, store, body.model);
1818
+ if (!isText(body.sessionId) || typeof body.text !== 'string' || body.text.trim() === '' || body.text.length > COMPLETE_INPUT || body.on !== undefined || body.model !== undefined) return json({ error: 'bad request' }, 400);
1819
+ const settings = await store.read();
1820
+ if (!settings.on) return json({ error: 'complete while typing is off' }, 409);
1821
+ const llm = get('llm');
1822
+ if (llm?.prepareCall === undefined) return json({ error: 'this dsh profile cannot call a model' }, 409);
1823
+ // Its own model while dsh lists it, else the prediction's, else dsh's default.
1824
+ const route = await routeOf(ctx, get, settings.model, (await predict.read()).model);
1825
+ if (route === undefined) return json({ error: 'no model is selected' }, 409);
1826
+ running.get(body.sessionId)?.abort();
1827
+ const mine = new AbortController();
1828
+ running.set(body.sessionId, mine);
1829
+ // The request's own signal also stops it: the browser aborts a fetch that a newer keystroke replaced.
1830
+ const signal = request.signal === undefined ? mine.signal : AbortSignal.any([mine.signal, request.signal]);
1831
+ try { return json(await completeTyping({ llm, sessionQuery: ctx.sessionQuery, route }, body.sessionId, body.text, signal)); }
1832
+ catch (error) {
1833
+ if (mine.signal.aborted) return json({ error: 'a newer completion replaced this one' }, 409);
1834
+ return json({ error: String(error?.message ?? error) }, Number.isInteger(error?.status) ? error.status : 502);
1835
+ } finally { if (running.get(body.sessionId) === mine) running.delete(body.sessionId); }
1836
+ },
1837
+ });
1838
+ }
1839
+
1840
+ /** Export as Markdown: at most this many characters of message text per export; the rest is cut and marked. */
1841
+ export const EXPORT_MAX = 4 * 1024 * 1024;
1842
+ /** A chat's messages for the Markdown export, oldest first: the user's own messages (text, and `[image]` or `[<type>]` for
1843
+ * other blocks) and the agent's reply text (no reasoning, no tool calls, no hidden context). Replies of one turn join
1844
+ * into one. Messages that Turn rollback or dsh-rewind-plugin withdrew are left out. Stops at `max` characters with
1845
+ * `truncated: true`. */
1846
+ export function chatTranscript(events, max = EXPORT_MAX) {
1847
+ const hidden = rollbackSpans(events, [ROLLBACK_SOURCE, REWIND_SOURCE]);
1848
+ const messages = [];
1849
+ let size = 0;
1850
+ for (const e of events) {
1851
+ if (hidden.some(([a, b]) => e.seq >= a && e.seq <= b)) continue;
1852
+ let role, text;
1853
+ if (e.type === 'user/message' && (e.data?.source === undefined || e.data.source?.kind === 'user')) {
1854
+ role = 'user';
1855
+ text = (Array.isArray(e.data.content) ? e.data.content : [])
1856
+ .map((b) => (b?.type === 'text' && typeof b.text === 'string' ? b.text : `\n[${b?.type === 'image' ? 'image' : String(b?.type ?? 'attachment')}]\n`)).join('').trim();
1857
+ } else if (e.type === 'assistant/message') {
1858
+ role = 'assistant';
1859
+ text = textBlocks(e.data?.message?.content).trim();
1860
+ } else continue;
1861
+ if (text === '') continue;
1862
+ const last = messages.at(-1);
1863
+ const add = role === 'assistant' && last?.role === 'assistant' ? `\n\n${text}` : text;
1864
+ if (size + add.length > max) return { messages, truncated: true };
1865
+ size += add.length;
1866
+ if (add !== text) last.text += add; else messages.push({ role, text });
1867
+ }
1868
+ return { messages, truncated: false };
1869
+ }
1870
+
1871
+ /** Export as Markdown: `GET ?sessionId` answers `{ project, messages, truncated }` from the chat's own log. Read-only; it
1872
+ * reads no project file. The browser makes the Markdown and copies or saves it. */
1873
+ function installExport(ctx) {
1874
+ ctx.connection.fetch.register({
1875
+ path: EXPORT_PATH, methods: ['GET'], requestBody: 'buffered',
1876
+ fetch: async (request) => {
1877
+ const sessionId = new URL(request.url).searchParams.get('sessionId');
1878
+ if (!isText(sessionId)) return json({ error: 'bad request' }, 400);
1879
+ try {
1880
+ const observation = await ctx.sessionQuery.observeSession(sessionId, { signal: request.signal, projectionMode: 'none' });
1881
+ try {
1882
+ const cwd = observation.header?.cwd;
1883
+ const project = typeof cwd === 'string' ? cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? '' : '';
1884
+ return json({ project, ...chatTranscript(observation.events ?? []) });
1885
+ } finally { observation[Symbol.dispose]?.(); }
1886
+ } catch (error) { return json({ error: String(error?.message ?? error) }, Number.isInteger(error?.status) ? error.status : 500); }
1887
+ },
1888
+ });
1889
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-composer-plus",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "DeepSeek Harness helpers: 11 extra UI languages (Türkçe, Español, Français, Deutsch, 日本語…), Changes panel, swipe-card feature ideas, sidebar search in message text, turn rollback with git file restore, delete chats to the Trash, input history, Shift+Tab /plan, one-click Continue, resume running chats after a restart, queue drag-and-drop, deeplinks, Auto Review allow-for-chat, notifications, iPhone access with the Tether app, automatic updates",
5
5
  "icon": "./assets/icon.svg",
6
6
  "license": "MIT",
@@ -73,7 +73,7 @@
73
73
  "assets/features/*.webp"
74
74
  ],
75
75
  "scripts": {
76
- "test": "node scripts/build-locales.mjs --check && node test/locale.test.mjs && node test/continue.test.mjs && node test/continue-host.test.mjs && node test/resume-restart.test.mjs && node test/content-search.test.mjs && node test/turn-rollback.test.mjs && node test/turn-rollback-client.test.mjs && node test/delete-chat.test.mjs && node test/project-name.test.mjs && node test/queue-drag.test.mjs && node test/plan-toggle.test.mjs && node test/keep-focus.test.mjs && node test/mobile-connect.test.mjs && node test/tether-gateway.test.mjs && node test/deeplink.test.mjs && node test/chat-grant.test.mjs && node test/notify.test.mjs && node test/changes.test.mjs && node test/feature-ideas.test.mjs && node test/feature-ideas-client.test.mjs && node test/project-status.test.mjs && node test/recent-projects.test.mjs && node test/project-tools.test.mjs && node test/status-order.test.mjs && node test/toggles.test.mjs && node test/update.test.mjs && node test/meta.test.mjs && node test/shots.test.mjs && node test/readme.test.mjs",
76
+ "test": "node scripts/build-locales.mjs --check && node test/locale.test.mjs && node test/continue.test.mjs && node test/continue-host.test.mjs && node test/resume-restart.test.mjs && node test/content-search.test.mjs && node test/turn-rollback.test.mjs && node test/turn-rollback-client.test.mjs && node test/delete-chat.test.mjs && node test/export-chat.test.mjs && node test/project-name.test.mjs && node test/queue-drag.test.mjs && node test/queue-move.test.mjs && node test/plan-toggle.test.mjs && node test/keep-focus.test.mjs && node test/mobile-connect.test.mjs && node test/tether-gateway.test.mjs && node test/tether-parity.test.mjs && node test/deeplink.test.mjs && node test/chat-grant.test.mjs && node test/notify.test.mjs && node test/changes.test.mjs && node test/feature-ideas.test.mjs && node test/feature-ideas-client.test.mjs && node test/project-status.test.mjs && node test/recent-projects.test.mjs && node test/project-tools.test.mjs && node test/project-picker.test.mjs && node test/predict.test.mjs && node test/predict-client.test.mjs && node test/complete.test.mjs && node test/complete-client.test.mjs && node test/status-order.test.mjs && node test/toggles.test.mjs && node test/update.test.mjs && node test/meta.test.mjs && node test/shots.test.mjs && node test/readme.test.mjs",
77
77
  "build:locales": "node scripts/build-locales.mjs",
78
78
  "prepublishOnly": "npm test"
79
79
  },