You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by lu...@apache.org on 2026/10/17 21:24:26 UTC
(maka) branch feat/desktop-conversation-tools created (now 1423f2bbff)
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a change to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
at 1423f2bbff fix(desktop): fit the composer's row beside the Workbar in a narrow window
This branch includes the following new commits:
new c82e66c3bc feat(desktop): continue a failed run
new e448c897e4 feat(desktop): show context use and compact in the composer
new bb47f5e2df feat(desktop): fork a task, whole or from a turn
new 1bd28011d7 feat(desktop): find in a conversation
new 1423f2bbff fix(desktop): fit the composer's row beside the Workbar in a narrow window
The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/05: feat(desktop): continue a failed run
Posted by lu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit c82e66c3bcabfcc7dd161199719123285a0e3966
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sun Oct 18 03:09:10 2026 +0800
feat(desktop): continue a failed run
The failed bar offers Continue first: agent.resume picks the run that
failed the turn up where it ended, with the composer's model. The failed
run's invocation id comes from the watch, or from agent.diagnostics when
the run ended before the conversation was opened; its high water from
agent.execution. Each parked reason shows as one sentence in the
composer's notice, and a run the Host will not continue (not resumable,
already continued, or not found, as in a fork) loses the button. A task
an executor runs has no Continue: the desktop starts no runs there. When
the Host does not answer, the notice says the run may or may not have
continued, and Continue stays off until the conversation shows a run or
the task is opened again. Send again stays after it when the turn has a
message to send. A turn started by a continued run has no message of its
own; it still gets the bar.
Generated-by: Claude Code
---
products/maka/desktop-shell/app/composer.js | 110 ++++++++++++++++++++++++++
products/maka/desktop-shell/app/main.js | 56 ++++++++-----
products/maka/desktop-shell/app/messages.js | 67 ++++++++++++++++
products/maka/desktop-shell/app/transcript.js | 36 ++++++++-
4 files changed, 248 insertions(+), 21 deletions(-)
diff --git a/products/maka/desktop-shell/app/composer.js b/products/maka/desktop-shell/app/composer.js
index 0b24275be1..d0fecf5eaf 100644
--- a/products/maka/desktop-shell/app/composer.js
+++ b/products/maka/desktop-shell/app/composer.js
@@ -40,6 +40,20 @@ import {
} from './theme.js';
import { t, onLanguageChange } from './locale.js';
+/** Why the Host did not continue a failed run (`AgentResumeParkReason`), in words. */
+const PARKED = {
+ closed: 'resumeClosed',
+ archived: 'resumeArchived',
+ busy: 'resumeBusy',
+ source_missing: 'resumeSourceMissing',
+ source_changed: 'resumeSourceChanged',
+ source_not_resumable: 'resumeNotResumable',
+ source_unreadable: 'resumeSourceUnreadable',
+ already_continued: 'resumeAlreadyContinued',
+ workspace_changed: 'resumeWorkspaceChanged',
+ safety_check_failed: 'resumeSafetyCheckFailed',
+};
+
/** The most files one message carries (`agent.send` `attachments`). */
const MAX_ATTACHMENTS = 8;
@@ -90,6 +104,13 @@ export class Composer {
this.choices = [];
this.sending = false;
this.stopping = false;
+ /** Whether Continue for a failed run is under way. */
+ this.resuming = false;
+ /**
+ * The last Continue the Host did not answer, `{ id, transcript, runsEnded }`,
+ * or null: it may have started a run, so Continue waits (awaitingResume).
+ */
+ this.unanswered = null;
/** Whether the model menu is open. */
this.menuOpen = false;
/** sessionId (or '' for a new task) -> the model chosen in the menu, which the next send uses. */
@@ -468,6 +489,95 @@ export class Composer {
}
}
+ /**
+ * Continue on a failed turn: `agent.resume` picks the run that failed it up
+ * where it ended, with the model the composer would send with. The run
+ * shows up through the watch. When the Host parks the request, the notice
+ * says why; a run it will not continue loses the button. When the Host
+ * does not answer, the run may have started, so the notice says so and
+ * Continue waits until the conversation shows a run (awaitingResume).
+ */
+ async resume(transcript, turnId) {
+ if (this.resuming || this.sending || this.awaitingResume(transcript)) return;
+ this.resuming = true;
+ this.hooks.changed();
+ try {
+ const reason = await this.continueRun(transcript, turnId);
+ if (reason === null) return;
+ log(`composer: resume parked: ${reason}`);
+ if (
+ reason === 'source_not_resumable' ||
+ reason === 'already_continued' ||
+ reason === 'source_missing'
+ ) {
+ transcript.noContinue.add(turnId);
+ }
+ this.hooks.report(t(PARKED[reason] ?? 'resumeParked', { value: reason }));
+ } catch (error) {
+ if (error.unanswered) {
+ this.unanswered = { id: transcript.id, transcript, runsEnded: transcript.runsEnded };
+ this.hooks.report(t('resumeUnknown'));
+ } else {
+ this.hooks.report(t('resumeFailed', { value: error.message }));
+ }
+ } finally {
+ this.resuming = false;
+ this.hooks.changed();
+ }
+ }
+
+ /** Asks the Host to continue the run that failed `turnId`: null once it started, else why it did not. */
+ async continueRun(transcript, turnId) {
+ const invocationId = await transcript.failedRun(turnId);
+ if (invocationId === null) return 'source_missing';
+ const found = await query(transcript.endpoint, 'execution', {
+ sessionId: transcript.id,
+ invocationId,
+ });
+ if (found.kind !== 'found') return 'source_missing';
+ const { model, thinkingLevel } = await this.selection(transcript);
+ let result;
+ try {
+ result = await operation(transcript.endpoint, 'resume', {
+ sessionId: transcript.id,
+ sourceInvocationId: invocationId,
+ sourceHighWater: found.execution.highWater,
+ model,
+ thinkingLevel,
+ });
+ } catch (error) {
+ log(`composer: resume of ${invocationId} got no answer: ${error.message}`);
+ throw Object.assign(new Error(error.message), { unanswered: true });
+ }
+ if (result.kind === 'parked') return result.reason;
+ log(`composer: resume started ${result.execution.invocationId} from ${invocationId}`);
+ // The new run shows up through the watch; this reads it now so the
+ // failed bar gives way before the first fact arrives.
+ await transcript.observeRun();
+ return null;
+ }
+
+ /**
+ * Whether the failed bar offers Continue for `turnId`: not for a run the
+ * Host will not continue, nor in a task an executor runs, where the
+ * composer starts no runs (selection).
+ */
+ offersContinue(transcript, turnId) {
+ return !transcript.noContinue.has(turnId) && transcript.backend?.kind !== 'executor';
+ }
+
+ /**
+ * Whether Continue in `transcript` waits after a Continue the Host did not
+ * answer: until the conversation shows a run start or end, or until it is
+ * opened again (a new Transcript, once it has read its rows).
+ */
+ awaitingResume(transcript) {
+ const unanswered = this.unanswered;
+ if (unanswered === null || transcript === null || transcript.id !== unanswered.id) return false;
+ if (transcript !== unanswered.transcript) return !transcript.ready;
+ return transcript.run === null && transcript.runsEnded === unanswered.runsEnded;
+ }
+
async stop(transcript) {
const run = transcript?.run;
if (!run || this.stopping) return;
diff --git a/products/maka/desktop-shell/app/main.js b/products/maka/desktop-shell/app/main.js
index d022318bec..98bf142284 100644
--- a/products/maka/desktop-shell/app/main.js
+++ b/products/maka/desktop-shell/app/main.js
@@ -726,21 +726,35 @@ export default class MakaDesktop extends View {
/**
* Above the composer when the newest turn failed: says so and offers to
- * send its message again. Picking the failed run up where it ended
- * (`agent.resume`) is not offered yet.
+ * continue the failed run where it stopped (`agent.resume`), unless the
+ * Host said it will not, and to send the turn's message again when there
+ * is one to send.
*/
failedBar(transcript, turn, cx) {
const m = palette(cx);
- return composerBar(
- icon('status-failed', 16, m.destructive),
- t('turnFailedNote'),
- turn.message === null
- ? null
- : controlButton('send-again', t('sendAgain'), 'outline', this.composer.sending, cx)
- .tooltip(t('sendAgainTip'))
- .on_click(() => this.composer.send(transcript, turn.message)),
- cx,
- );
+ const busy = this.composer.sending || this.composer.resuming;
+ const buttons = [];
+ if (this.composer.offersContinue(transcript, turn.turnId)) {
+ buttons.push(
+ controlButton(
+ 'continue-run',
+ t('continueRun'),
+ 'primary',
+ busy || this.composer.awaitingResume(transcript),
+ cx,
+ )
+ .tooltip(t('continueRunTip'))
+ .on_click(() => this.composer.resume(transcript, turn.turnId)),
+ );
+ }
+ if (turn.message !== null) {
+ buttons.push(
+ controlButton('send-again', t('sendAgain'), 'outline', busy, cx)
+ .tooltip(t('sendAgainTip'))
+ .on_click(() => this.composer.send(transcript, turn.message)),
+ );
+ }
+ return composerBar(icon('status-failed', 16, m.destructive), t('turnFailedNote'), buttons, cx);
}
/**
@@ -752,9 +766,15 @@ export default class MakaDesktop extends View {
return composerBar(
icon('triangle-alert', 16, m.warning),
t('workhubNeedsSubagent'),
- controlButton('workhub-subagents', t('workhubSetUpSubagents'), 'outline', false, cx).on_click(
- () => this.settings.show('subagents'),
- ),
+ [
+ controlButton(
+ 'workhub-subagents',
+ t('workhubSetUpSubagents'),
+ 'outline',
+ false,
+ cx,
+ ).on_click(() => this.settings.show('subagents')),
+ ],
cx,
);
}
@@ -971,8 +991,8 @@ function runState(transcript) {
return transcript.run ? t('working') : null;
}
-/** A bar above the composer, in its column: a glyph, a line, and a button at its end, or none. */
-function composerBar(glyph, words, button, cx) {
+/** A bar above the composer, in its column: a glyph, a line, and the buttons at its end. */
+function composerBar(glyph, words, buttons, cx) {
const m = palette(cx);
return h_flex()
.flex_none()
@@ -995,7 +1015,7 @@ function composerBar(glyph, words, button, cx) {
.bg(m.plate)
.child(glyph)
.child(text(words, 'body', m.ink).flex_1().min_w_0())
- .when(button !== null, (el) => el.child(button)),
+ .children(buttons),
);
}
diff --git a/products/maka/desktop-shell/app/messages.js b/products/maka/desktop-shell/app/messages.js
index 607a016a80..c39da4ab8f 100644
--- a/products/maka/desktop-shell/app/messages.js
+++ b/products/maka/desktop-shell/app/messages.js
@@ -328,6 +328,73 @@ export const MESSAGES = {
'把这一轮的消息再发送一次',
'把這一輪的訊息再傳送一次',
],
+ continueRun: ['Continue', '继续', '繼續'],
+ continueRunTip: [
+ 'Continue the failed run from where it stopped',
+ '从失败的运行中断处继续',
+ '從失敗的執行中斷處繼續',
+ ],
+ resumeFailed: ['Continue: {value}', '继续失败:{value}', '繼續失敗:{value}'],
+ resumeParked: [
+ 'The Host did not continue the run ({value}).',
+ 'Host 没有继续这次运行({value})。',
+ 'Host 沒有繼續這次執行({value})。',
+ ],
+ resumeClosed: [
+ 'The Host is closing, so the run cannot continue.',
+ 'Host 正在关闭,无法继续运行。',
+ 'Host 正在關閉,無法繼續執行。',
+ ],
+ resumeUnknown: [
+ 'The Host did not answer, so the run may or may not have continued. Continue comes back once this task shows a run, or after you open the task again.',
+ 'Host 没有回应,运行可能已经继续,也可能没有。任务显示出运行后,或重新打开任务后,才能再次继续。',
+ 'Host 沒有回應,執行可能已經繼續,也可能沒有。任務顯示出執行後,或重新開啟任務後,才能再次繼續。',
+ ],
+ resumeArchived: [
+ 'This task is archived, so the run cannot continue.',
+ '这个任务已归档,无法继续运行。',
+ '這個任務已封存,無法繼續執行。',
+ ],
+ resumeBusy: [
+ 'Another run is going in this task. Try again when it ends.',
+ '这个任务正有一次运行在进行,结束后再试。',
+ '這個任務正有一次執行在進行,結束後再試。',
+ ],
+ resumeSourceMissing: [
+ 'The failed run could not be found.',
+ '找不到失败的那次运行。',
+ '找不到失敗的那次執行。',
+ ],
+ resumeSourceChanged: [
+ 'The failed run changed since it was read. Try again.',
+ '失败的运行在读取后有了变化,请再试一次。',
+ '失敗的執行在讀取後有了變化,請再試一次。',
+ ],
+ resumeNotResumable: [
+ 'This run cannot be continued. Send the message again instead.',
+ '这次运行无法继续,请改为重新发送消息。',
+ '這次執行無法繼續,請改為重新傳送訊息。',
+ ],
+ resumeSourceUnreadable: [
+ 'The failed run could not be read, so it cannot continue.',
+ '无法读取失败的运行,因此不能继续。',
+ '無法讀取失敗的執行,因此不能繼續。',
+ ],
+ resumeAlreadyContinued: [
+ 'This run was already continued.',
+ '这次运行已经继续过了。',
+ '這次執行已經繼續過了。',
+ ],
+ resumeWorkspaceChanged: [
+ "The task's folder changed since the run, so it cannot continue.",
+ '任务的文件夹在运行后有了变化,无法继续。',
+ '任務的資料夾在執行後有了變化,無法繼續。',
+ ],
+ resumeSafetyCheckFailed: [
+ 'The Host could not confirm it is safe to continue this run.',
+ 'Host 无法确认继续这次运行是安全的。',
+ 'Host 無法確認繼續這次執行是安全的。',
+ ],
// How long ago, in the transcript (transcript.js relativeTime)
justNow: ['just now', '刚刚', '剛剛'],
diff --git a/products/maka/desktop-shell/app/transcript.js b/products/maka/desktop-shell/app/transcript.js
index a33a6229b7..43acbd6cfc 100644
--- a/products/maka/desktop-shell/app/transcript.js
+++ b/products/maka/desktop-shell/app/transcript.js
@@ -226,6 +226,10 @@ export class Transcript {
* status on each).
*/
this.runsEnded = 0;
+ /** turnId -> the invocation id of its run, from the watch's `opened` and `ended` facts. */
+ this.invocations = new Map();
+ /** Turns whose failed run the Host will not continue: Continue is not offered for them. */
+ this.noContinue = new Set();
this.latestKnown = 0;
this.watchHandle = null;
this.watchLast = 0;
@@ -380,8 +384,10 @@ export class Transcript {
* `{ turnId, message }`, with the whole text of the message that started
* it, or null as `message` when only part of that text is loaded, it has
* none, it came with files (the files are not at hand to send again), or a
- * WorkHub notice started the turn. Null otherwise, and while newer history
- * is still to be read. A stopped turn is left alone: the user stopped it.
+ * WorkHub notice started the turn. A turn whose message is not loaded, or
+ * that a continued run started (it has no message of its own), has a null
+ * `message` too. Null otherwise, and while newer history is still to be
+ * read. A stopped turn is left alone: the user stopped it.
*/
failedTurn() {
if (!this.ready || this.after !== null) return null;
@@ -389,7 +395,7 @@ export class Transcript {
const last = this.rows.at(-1);
if (last?.timing?.finished?.outcome !== 'failed') return null;
const start = this.rows.find((row) => row.turnId === last.turnId && row.role === 'user');
- if (!start) return null;
+ if (!start) return { turnId: last.turnId, message: null };
// A turn a WorkHub notice started is WorkHub's to start again, not the user's.
const notice = originOf(start) !== null;
const whole = start.fragments[0]?.offset === 0 && utf8Length(start.text) === start.totalBytes;
@@ -398,6 +404,28 @@ export class Transcript {
return { turnId: last.turnId, message: message.trim() !== '' ? message : null };
}
+ /**
+ * The invocation id of the run that failed `turnId`, for `agent.resume`:
+ * from the watch when the run ended while this was open, else from the
+ * newest execution entries of `agent.diagnostics` (a few pages at most).
+ * Null when neither has it.
+ */
+ async failedRun(turnId) {
+ const seen = this.invocations.get(turnId);
+ if (seen !== undefined) return seen;
+ let position = { kind: 'latest' };
+ for (let pages = 0; pages < 4; pages += 1) {
+ const page = await query(this.endpoint, 'diagnostics', { sessionId: this.id, position });
+ const entry = page.entries.find(
+ (each) => each.detail?.kind === 'execution' && each.detail.invocation?.turn_id === turnId,
+ );
+ if (entry) return entry.detail.invocation.invocation_id;
+ if (page.nextBefore === null || page.nextBefore === undefined) return null;
+ position = { kind: 'before', through: page.through, sequence: page.nextBefore };
+ }
+ return null;
+ }
+
/** Stops the live updates. A pending `next()` resolves with null. */
async close() {
this.closed = true;
@@ -442,6 +470,7 @@ export class Transcript {
const fact = event.fact;
switch (fact.kind) {
case 'opened':
+ if (event.turnId) this.invocations.set(event.turnId, event.invocationId);
if (event.sequence > this.runThrough) {
this.run = { invocationId: event.invocationId, turnId: event.turnId, state: 'running' };
this.runThrough = event.sequence;
@@ -505,6 +534,7 @@ export class Transcript {
canonicalChanged = true;
break;
case 'ended':
+ if (event.turnId) this.invocations.set(event.turnId, event.invocationId);
this.closeLive(event.sequence, event.invocationId);
this.parts = this.parts.filter((open) => open.invocationId !== event.invocationId);
if (event.sequence > this.runThrough) this.runsEnded += 1;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 03/05: feat(desktop): fork a task, whole or from a turn
Posted by lu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit bb47f5e2df36c7a795d59e0085797b0243e4a0fd
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sun Oct 18 03:32:33 2026 +0800
feat(desktop): fork a task, whole or from a turn
The task menu (the "..." button and right-click) gets Fork, which copies
the whole history into a new task (agent.fork with no turn) and selects
it. It is offered while the task is idle: for a running task the Host
answers history_unavailable. A finished turn's footer gets a Fork button
at its end, which forks through that turn; the list takes one click
handler for its rows, so the press before the click tells the button
from the rest of the footer, which still copies the reply. WorkHub's
conversation does not offer it: the coordinator's forks are not tasks
the desktop can open.
The fork is titled after its source with " (fork)", the title shortened
to fit 128 characters. A revision conflict reads the task again and
tries once more; each refusal is one sentence; a call that got no answer
says the fork may or may not have been made and is not sent again.
A fork's header shows "Forked from" and the source's title, muted,
opening the source. An archived source is read with agent.observe; a
deleted one is named as deleted, without a link.
Generated-by: Claude Code
---
products/maka/desktop-shell/app/icons/fork.svg | 20 ++++
products/maka/desktop-shell/app/main.js | 146 ++++++++++++++++++++++--
products/maka/desktop-shell/app/messages.js | 83 ++++++++++++++
products/maka/desktop-shell/app/sessions.js | 112 +++++++++++++++++-
products/maka/desktop-shell/app/transcript.js | 151 +++++++++++++++++--------
5 files changed, 451 insertions(+), 61 deletions(-)
diff --git a/products/maka/desktop-shell/app/icons/fork.svg b/products/maka/desktop-shell/app/icons/fork.svg
new file mode 100644
index 0000000000..dd3ca8b2fa
--- /dev/null
+++ b/products/maka/desktop-shell/app/icons/fork.svg
@@ -0,0 +1,20 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="4" cy="3.75" r="1.75"/><circle cx="12" cy="3.75" r="1.75"/><circle cx="8" cy="12.25" r="1.75"/><path d="M4 5.5v1A1.5 1.5 0 0 0 5.5 8h5A1.5 1.5 0 0 0 12 6.5v-1"/><path d="M8 8v2.5"/></svg>
diff --git a/products/maka/desktop-shell/app/main.js b/products/maka/desktop-shell/app/main.js
index b526d36670..830dfce43c 100644
--- a/products/maka/desktop-shell/app/main.js
+++ b/products/maka/desktop-shell/app/main.js
@@ -33,7 +33,7 @@
// export default { debug: true, run: async ({ app, cx, log }) => { ... } };
import { View, div } from 'gpui-kit';
-import { v_flex, h_flex, h_resizable, resizable_panel } from 'gpui-base';
+import { v_flex, h_flex, h_resizable, resizable_panel, Button } from 'gpui-base';
import { query, operation, log, setDebug } from './host.js';
import { SessionCatalog, SidebarState, sidebar } from './sessions.js';
import { Transcript, transcriptPane } from './transcript.js';
@@ -46,7 +46,15 @@ import { WorkHub, workhubTabs, workhubBody, chatHint } from './workhub.js';
import { Search, searchPage } from './search.js';
import { usable } from './subagents.js';
import { Workbar, WORKBAR_WIDTH, workbarPane, workbarButton } from './workbar.js';
-import { followAppearance, palette, text, icon, controlButton, ghostButton } from './theme.js';
+import {
+ followAppearance,
+ palette,
+ typeset,
+ text,
+ icon,
+ controlButton,
+ ghostButton,
+} from './theme.js';
import { t, onLanguageChange } from './locale.js';
/**
@@ -102,6 +110,8 @@ export default class MakaDesktop extends View {
this.cx.notify();
},
report,
+ // A turn footer's Fork: the sidebar's fork, through that turn.
+ fork: (session, turnId) => this.sidebarUi.fork(session, turnId),
};
this.hooks = hooks;
this.catalog = new SessionCatalog({
@@ -170,10 +180,18 @@ export default class MakaDesktop extends View {
archived: (sessionId) => {
if (this.transcript?.id === sessionId) this.home();
},
+ forked: (session) => this.select(session),
focusRoot: () => this.rootFocus.focus(),
},
cx,
);
+ /**
+ * id -> what the header of a fork names its source by when the sidebar
+ * does not list it (an archived task): `{ session }` as `agent.observe`
+ * read it, `{ gone: true }` when the Host has no such task, `{ failed:
+ * true }` when it could not be read, or null while it is read.
+ */
+ this.forkSources = new Map();
this.creating = false;
this.error = null;
this.sidebarHidden = false;
@@ -608,7 +626,15 @@ export default class MakaDesktop extends View {
const folder = transcript === null ? this.startFolder() : null;
return this.conversation(
el
- .child(this.header(transcript?.session.title ?? '', runState(transcript), null, cx))
+ .child(
+ this.header(
+ transcript?.session.title ?? '',
+ runState(transcript),
+ null,
+ cx,
+ this.forkOrigin(transcript, cx),
+ ),
+ )
.child(this.connectionStrip(cx)),
transcript,
{
@@ -630,6 +656,80 @@ export default class MakaDesktop extends View {
);
}
+ /**
+ * After the header's title on a task forked from another: "Forked from" and
+ * the source's title, muted, opening the source. The title is the
+ * sidebar's, else what `agent.observe` reads once (an archived source); a
+ * source the Host no longer has is named as deleted, without a link.
+ * Null for a task that is not a fork, and while the source is read.
+ */
+ forkOrigin(transcript, cx) {
+ const sessionId = transcript?.session.branch?.sessionId ?? null;
+ if (sessionId === null) return null;
+ const m = palette(cx);
+ const source = this.forkSource(sessionId);
+ if (source === null) return null;
+ if (source.gone === true) {
+ return text(t('forkedFromRemoved'), 'small', m.inkMuted).flex_none();
+ }
+ const label =
+ source.session === undefined
+ ? t('forkedFromUnknown')
+ : t('forkedFrom', { title: source.session.title });
+ return typeset(Button.new('forked-from'), 'small')
+ .flex_initial()
+ .min_w_0()
+ .max_w(360)
+ .h(24)
+ .px(6)
+ .items_center()
+ .rounded(6)
+ .text_color(m.inkMuted)
+ .hover((style) => style.bg(m.hover))
+ .tooltip(label)
+ .on_click(() => this.openForkSource(sessionId))
+ .child(div().min_w_0().truncate().child(label));
+ }
+
+ /**
+ * The source of a fork, as forkSources keeps it: the sidebar's entry when
+ * it lists the task, else the cached read, else null after starting it.
+ */
+ forkSource(sessionId) {
+ const listed = this.catalog.sessions.find((entry) => entry.id === sessionId);
+ if (listed !== undefined) return { session: listed };
+ if (this.forkSources.has(sessionId)) return this.forkSources.get(sessionId);
+ this.forkSources.set(sessionId, null);
+ query('agent', 'observe', { sessionId }).then(
+ (observed) => {
+ this.forkSources.set(sessionId, { session: observed.session });
+ this.cx.notify();
+ },
+ (error) => {
+ log(`fork source ${sessionId}: ${error.message}`);
+ const gone = error.message.includes('session_unavailable');
+ this.forkSources.set(sessionId, gone ? { gone: true } : { failed: true });
+ this.cx.notify();
+ },
+ );
+ return null;
+ }
+
+ /** The header's "Forked from": opens the source, archived or not. */
+ async openForkSource(sessionId) {
+ const known = this.forkSource(sessionId)?.session;
+ if (known !== undefined) {
+ await this.select(known);
+ return;
+ }
+ try {
+ const observed = await query('agent', 'observe', { sessionId });
+ await this.select(observed.session);
+ } catch (error) {
+ this.report(t('forkSourceFailed', { value: error.message }));
+ }
+ }
+
/**
* The plate's content while WorkHub is open: its header, with the tabs once
* it is set up, the connection strip, then its conversation, drawn as a
@@ -836,11 +936,12 @@ export default class MakaDesktop extends View {
/**
* The plate's 48px header: `title`, and what its conversation is doing
* (`state`, or null). `controls`, when given, sit in the middle of the
- * plate, with the state after them. With the sidebar hidden it also
- * carries the window controls, clear of the traffic lights. Beside a
- * conversation the Workbar's button ends it.
+ * plate, with the state after them; `origin`, when given, right after the
+ * title (a fork's source). With the sidebar hidden it also carries the
+ * window controls, clear of the traffic lights. Beside a conversation the
+ * Workbar's button ends it.
*/
- header(title, state, controls, cx) {
+ header(title, state, controls, cx, origin = null) {
const m = palette(cx);
const hidden = this.sidebarHidden;
const toggle = this.workbarTarget() === null ? null : workbarButton(this.workbar, cx);
@@ -863,10 +964,33 @@ export default class MakaDesktop extends View {
.child(dragArea().w(8).h_full()),
)
.when(!hidden, (el) => el.child(dragArea().w(20).h_full()))
- .child(
- side()
- .child(text(title, 'strong', m.ink).flex_1().min_w_0().truncate())
- .when(controls === null && stateText !== null, (el) => el.child(stateText)),
+ .when(origin === null, (el) =>
+ el.child(
+ side()
+ .child(text(title, 'strong', m.ink).flex_1().min_w_0().truncate())
+ .when(controls === null && stateText !== null, (el) => el.child(stateText)),
+ ),
+ )
+ // The origin is a button, so it stands between two parts that move the
+ // window: the title's, as wide as the title, and the rest.
+ .when(origin !== null, (el) =>
+ el
+ .child(
+ h_flex()
+ .flex_initial()
+ .min_w_0()
+ .h_full()
+ .items_center()
+ .window_control_area('drag')
+ .child(text(title, 'strong', m.ink).min_w_0().truncate()),
+ )
+ .child(origin.ml(8))
+ .child(
+ side()
+ .min_w(12)
+ .justify_end()
+ .when(controls === null && stateText !== null, (el) => el.child(stateText)),
+ ),
);
return h_flex()
.flex_none()
diff --git a/products/maka/desktop-shell/app/messages.js b/products/maka/desktop-shell/app/messages.js
index 0b737a81ed..d6c3e90676 100644
--- a/products/maka/desktop-shell/app/messages.js
+++ b/products/maka/desktop-shell/app/messages.js
@@ -100,6 +100,89 @@ export const MESSAGES = {
'請先停止此任務並處理佇列訊息,再封存或刪除。',
],
+ // Forking a task: the menu, a turn's footer (transcript.js) and the header
+ // of a fork (main.js).
+ forkTask: ['Fork', '分叉', '分岔'],
+ forkFromHere: [
+ 'Fork from here: a new task with the history up to this turn',
+ '从这里分叉:用到这一轮为止的历史新建任务',
+ '從這裡分岔:用到這一輪為止的歷史新建任務',
+ ],
+ forkSuffix: [' (fork)', '(分叉)', '(分岔)'],
+ forkedFrom: ['Forked from {title}', '分叉自 {title}', '分岔自 {title}'],
+ forkedFromRemoved: [
+ 'Forked from a task that was deleted',
+ '分叉自一个已删除的任务',
+ '分岔自一個已刪除的任務',
+ ],
+ forkedFromUnknown: ['Forked from another task', '分叉自另一个任务', '分岔自另一個任務'],
+ forkSourceFailed: [
+ 'Couldn’t open the task this one was forked from: {value}',
+ '无法打开此任务分叉自的任务:{value}',
+ '無法開啟此任務分岔自的任務:{value}',
+ ],
+ forkFailed: ['Couldn’t fork the task: {value}', '分叉任务失败:{value}', '分岔任務失敗:{value}'],
+ forkUnknown: [
+ 'The Host did not answer the fork, so it may or may not have been made. Check the task list before forking again.',
+ 'Host 没有回应分叉请求,分叉可能已经创建,也可能没有。再次分叉前请先查看任务列表。',
+ 'Host 沒有回應分岔請求,分岔可能已經建立,也可能沒有。再次分岔前請先查看任務列表。',
+ ],
+ forkRejected: [
+ 'The Host did not fork the task ({value}).',
+ 'Host 没有分叉此任务({value})。',
+ 'Host 沒有分岔此任務({value})。',
+ ],
+ forkTitleInvalid: [
+ 'The Host did not accept the title for the fork.',
+ 'Host 不接受分叉任务的标题。',
+ 'Host 不接受分岔任務的標題。',
+ ],
+ forkLabelsInvalid: [
+ 'The Host did not accept the labels for the fork.',
+ 'Host 不接受分叉任务的标签。',
+ 'Host 不接受分岔任務的標籤。',
+ ],
+ forkToolsUnavailable: [
+ 'The tools of this task are not available, so it cannot be forked.',
+ '此任务的工具不可用,无法分叉。',
+ '此任務的工具無法使用,無法分岔。',
+ ],
+ forkBusy: [
+ 'Something is running in this task. Fork it when it ends.',
+ '此任务正在运行,结束后再分叉。',
+ '此任務正在執行,結束後再分岔。',
+ ],
+ forkWorkspaceUnavailable: [
+ 'The folder of this task is not available, so it cannot be forked.',
+ '此任务的文件夹不可用,无法分叉。',
+ '此任務的資料夾無法使用,無法分岔。',
+ ],
+ forkSessionUnavailable: [
+ 'This task is no longer available, so it cannot be forked.',
+ '此任务已不可用,无法分叉。',
+ '此任務已無法使用,無法分岔。',
+ ],
+ forkHistoryUnavailable: [
+ 'The history of this task cannot be copied now. If something is running, fork it when it ends.',
+ '此任务的历史现在无法复制。如果任务正在运行,请在结束后再分叉。',
+ '此任務的歷史現在無法複製。如果任務正在執行,請在結束後再分岔。',
+ ],
+ forkWhileRunning: [
+ 'A task can be forked whole while nothing runs in it; a finished turn can be forked from its footer.',
+ '任务中没有运行时才能整体分叉;已结束的一轮可以从它下方分叉。',
+ '任務中沒有執行時才能整體分岔;已結束的一輪可以從它下方分岔。',
+ ],
+ forkManagedSession: [
+ 'WorkHub manages this task, so it cannot be forked.',
+ '此任务由 WorkHub 管理,无法分叉。',
+ '此任務由 WorkHub 管理,無法分岔。',
+ ],
+ forkClosed: [
+ 'The Host is closing, so the task cannot be forked.',
+ 'Host 正在关闭,无法分叉任务。',
+ 'Host 正在關閉,無法分岔任務。',
+ ],
+
// Ages in lists (theme.js)
ageNow: ['now', '刚刚', '剛剛'],
diff --git a/products/maka/desktop-shell/app/sessions.js b/products/maka/desktop-shell/app/sessions.js
index 0ceb325fba..5516ddf64e 100644
--- a/products/maka/desktop-shell/app/sessions.js
+++ b/products/maka/desktop-shell/app/sessions.js
@@ -243,6 +243,66 @@ export async function changeSession(session, action) {
}
}
+/** Why the Host did not fork a task (`AgentRejection`), in words. */
+const FORK_REJECTED = {
+ title_invalid: 'forkTitleInvalid',
+ labels_invalid: 'forkLabelsInvalid',
+ tools_unavailable: 'forkToolsUnavailable',
+ busy: 'forkBusy',
+ workspace_unavailable: 'forkWorkspaceUnavailable',
+ session_unavailable: 'forkSessionUnavailable',
+ history_unavailable: 'forkHistoryUnavailable',
+ managed_session: 'forkManagedSession',
+ closed: 'forkClosed',
+};
+
+/**
+ * The title of a fork of a task titled `title`: the title and a suffix
+ * that says it is a fork, the title shortened so both fit in what the Host
+ * takes.
+ */
+export function forkTitle(title) {
+ const suffix = t('forkSuffix');
+ const room = MAX_TITLE - [...suffix].length;
+ return [...title].slice(0, room).join('').trimEnd() + suffix;
+}
+
+/**
+ * Forks `session` (`agent.fork`) into a new task titled `title`: all of its
+ * history, or the history through the turn `turnId`. A revision conflict
+ * reads the session again and tries once more, as a rename does. Resolves
+ * with the new session. A refusal throws a whole sentence (`error.whole`);
+ * so does a call that got no answer, since the fork may have been made, and
+ * it is not sent again.
+ */
+export async function forkSession(session, turnId, title) {
+ let current = session;
+ for (let attempt = 0; ; attempt += 1) {
+ let result;
+ try {
+ result = await operation('agent', 'fork', {
+ sessionId: current.id,
+ expectedRevision: current.revision,
+ turnId,
+ title,
+ labels: [],
+ });
+ } catch (error) {
+ log(`sessions: fork of ${current.id} got no answer: ${error.message}`);
+ throw whole(t('forkUnknown'));
+ }
+ if (result.kind === 'forked') return result.session;
+ if (result.kind === 'rejected') {
+ throw whole(t(FORK_REJECTED[result.reason] ?? 'forkRejected', { value: result.reason }));
+ }
+ if (result.kind !== 'revision_conflict') {
+ throw new Error(t('unexpectedAnswer', { value: result.kind }));
+ }
+ if (attempt > 0) throw new Error(t('taskChangedMeanwhile'));
+ current = (await query('agent', 'observe', { sessionId: current.id })).session;
+ }
+}
+
function whole(message) {
const error = new Error(message);
error.whole = true;
@@ -273,10 +333,11 @@ export class SidebarState {
* view's `init`, whose context it keeps for the waits below.
* @param {{ changed: () => void, report: (message: string) => void,
* renamed: (session: object) => void, archived: (sessionId: string) => void,
- * focusRoot: () => void }} hooks
+ * forked: (session: object) => void, focusRoot: () => void }} hooks
* `renamed` gets the session as the Host committed the new title,
- * `archived` the id of a task the Host archived, and `focusRoot` gives
- * the keyboard back to the window after a rename ends from it
+ * `archived` the id of a task the Host archived, `forked` the new task a
+ * fork made, and `focusRoot` gives the keyboard back to the window after
+ * a rename ends from it
*/
constructor(hooks, cx) {
this.hooks = hooks;
@@ -307,6 +368,8 @@ export class SidebarState {
* drops it, or lists it again at a later revision (restored).
*/
this.archiving = new Map();
+ /** Ids of the tasks the Host is forking. */
+ this.forking = new Set();
this.name = InputState.new({ placeholder: t('renameTask') });
onLanguageChange(() => this.name.set_placeholder(t('renameTask')));
// Enter saves; leaving the field saves too, as Finder does. Escape is
@@ -491,6 +554,34 @@ export class SidebarState {
this.changed();
}
+ /**
+ * Forks the task: all of its history (the menu), or through the turn
+ * `turnId` (a turn's footer). The new task is selected once the Host made
+ * it (`forked`).
+ */
+ async fork(session, turnId = null) {
+ this.menu = null;
+ if (this.forking.has(session.id)) {
+ this.changed();
+ return;
+ }
+ this.forking.add(session.id);
+ this.changed();
+ try {
+ const forked = await forkSession(session, turnId, forkTitle(this.title(session)));
+ log(
+ `sessions: forked ${session.id}${turnId === null ? '' : ` through ${turnId}`} as ${forked.id}`,
+ );
+ this.hooks.forked(forked);
+ } catch (error) {
+ log(`sessions: forking ${session.id} failed: ${error.message}`);
+ this.hooks.report(changeFailure(error, (value) => t('forkFailed', { value })));
+ } finally {
+ this.forking.delete(session.id);
+ this.changed();
+ }
+ }
+
/**
* Archives the task. The row shows the running glyph until the catalog
* drops it; the window leaves the task when it is open (`archived`).
@@ -788,8 +879,9 @@ function taskRow(session, selected, ui, select, cx) {
}
/**
- * The "…" button and the menu it opens: Rename (F2), Copy task ID, then
- * Archive, which only an idle task offers. The button's press opens the
+ * The "…" button and the menu it opens: Rename (F2), Fork, Copy task ID,
+ * then Archive. Fork and Archive are offered only for an idle task (the
+ * Host does not copy the whole history of a task while it runs). The button's press opens the
* menu and goes no further, so the row under it is not selected; the menu
* hangs 8 under the row with its end on the row's end, as the native
* client's does (the button sits 8 in from the row's end and 6 above its
@@ -819,6 +911,16 @@ function taskMenu(session, ui, cx) {
() => ui.startRename(session),
),
)
+ .child(
+ menuRow(
+ 'task-fork',
+ t('forkTask'),
+ { icon: 'fork', disabled: !idle || ui.forking.has(session.id) },
+ cx,
+ )
+ .when(!idle, (el) => el.tooltip(t('forkWhileRunning')))
+ .on_click(() => ui.fork(session)),
+ )
.child(
menuRow('task-copy-id', t('copyTaskId'), { icon: 'copy' }, cx).on_click((_, cx) =>
ui.copyId(session, cx),
diff --git a/products/maka/desktop-shell/app/transcript.js b/products/maka/desktop-shell/app/transcript.js
index 43acbd6cfc..1a3218c7f6 100644
--- a/products/maka/desktop-shell/app/transcript.js
+++ b/products/maka/desktop-shell/app/transcript.js
@@ -65,6 +65,11 @@ import { t, tn, language } from './locale.js';
const NEAR_TOP = 3;
/** How many rows back to look for a tool call when its result arrives. */
const TOOL_PAIR_WINDOW = 64;
+/** The reading column: at most this wide, with this much on each side (transcriptItem). */
+const COLUMN_WIDTH = 720;
+const COLUMN_GUTTER = 24;
+/** The footer's Fork button, square at the end of the column (turnFooter). */
+const FORK_BUTTON = 24;
const FIELD_ORDER = { thinking: 0, body: 1 };
@@ -245,6 +250,12 @@ export class Transcript {
this.olderError = null;
/** The footer whose turn was just copied, for two seconds. */
this.copied = null;
+ /**
+ * Where the last left press in the transcript was, `{ x, width }` against
+ * the list: the click that follows tells a footer's Fork button from the
+ * rest of the footer by it (see onForkButton).
+ */
+ this.press = null;
/** The list items last built from the rows (see displayItems). */
this.view = null;
/**
@@ -786,8 +797,12 @@ export class Transcript {
return;
}
if (key.startsWith('footer/')) {
- if (!this.view?.items.find((entry) => entry.key === key)?.copies) return;
const turnId = key.slice('footer/'.length);
+ if (this.forks() && this.onForkButton()) {
+ this.hooks.fork(this.session, turnId);
+ return;
+ }
+ if (!this.view?.items.find((entry) => entry.key === key)?.copies) return;
const reply = this.rows
.filter((row) => row.turnId === turnId && row.role === 'assistant')
.map((row) => row.text)
@@ -817,6 +832,32 @@ export class Transcript {
this.hooks.changed();
}
+ /** Whether turn footers offer Fork: a task's conversation, not WorkHub's. */
+ forks() {
+ return this.endpoint === 'agent' && typeof this.hooks.fork === 'function';
+ }
+
+ /** A left press in the transcript, from the area around the list. */
+ pressed(event) {
+ const { local_position: at, bounds } = event;
+ this.press = at && bounds ? { x: at.x, width: bounds.width } : null;
+ }
+
+ /**
+ * Whether the press before a footer's click was on its Fork button, the
+ * last FORK_BUTTON of the reading column. List rows take one click
+ * handler for the whole list, so the press's place tells the button from
+ * the rest of the footer, which copies.
+ */
+ onForkButton() {
+ const press = this.press;
+ this.press = null;
+ if (press === null) return false;
+ const column = Math.min(COLUMN_WIDTH, press.width - 2 * COLUMN_GUTTER);
+ const end = (press.width + column) / 2;
+ return press.x >= end - FORK_BUTTON && press.x <= end;
+ }
+
/**
* The start of a tool row's `arguments` or `result`, or of the value at
* `path` in it, as `{ text, complete, totalBytes, tail, failed? }`; null until
@@ -1065,59 +1106,63 @@ export function transcriptPane(transcript, loadOlder, cx, empty = null) {
const items = displayItems(transcript);
const hasRows = transcript.rows.length + transcript.pending.length + transcript.live.length > 0;
const id = `transcript-${transcript.id}`;
- return v_flex()
- .id(`${id}-area`)
- .relative()
- .flex_1()
- .min_h_0()
- .when(!transcript.ready || !hasRows, (el) =>
- el
- .items_center()
- .justify_center()
- .child(
- transcript.ready && empty !== null
- ? empty
- : text(transcript.ready ? t('noMessagesYet') : t('loading'), 'body', m.inkMuted),
- ),
- )
- .when(transcript.ready && hasRows, (el) =>
- el
- .child(
- list(
- id,
- items.length,
- (index) => items[index].key,
- (index, cx) => transcriptItem(items[index], transcript, cx),
+ return (
+ v_flex()
+ .id(`${id}-area`)
+ .relative()
+ .flex_1()
+ .min_h_0()
+ // A footer's click comes on release; the press before it says where it was.
+ .on_mouse_down('left', (event) => transcript.pressed(event))
+ .when(!transcript.ready || !hasRows, (el) =>
+ el
+ .items_center()
+ .justify_center()
+ .child(
+ transcript.ready && empty !== null
+ ? empty
+ : text(transcript.ready ? t('noMessagesYet') : t('loading'), 'body', m.inkMuted),
+ ),
+ )
+ .when(transcript.ready && hasRows, (el) =>
+ el
+ .child(
+ list(
+ id,
+ items.length,
+ (index) => items[index].key,
+ (index, cx) => transcriptItem(items[index], transcript, cx),
+ )
+ // Opens at the newest row and stays there while a reply
+ // streams, until the reader scrolls up. Opened at an anchor, it
+ // opens at its top, the anchor's row, and keeps the reader's top
+ // row in place as pages are put above and added below, until the
+ // reader reaches the newest row or sends (Transcript.showing).
+ .with_follow_mode(transcript.anchored ? 'normal' : 'tail')
+ // Reported after the frame, however the range changed: a
+ // wheel, a scrollbar drag, or rows that do not fill the view.
+ .on_visible_range_change((range, shown) => {
+ log(`transcript: showing ${range.start}..${range.end} of ${shown}`);
+ transcript.showing(range, shown);
+ if (range.start < NEAR_TOP && transcript.before !== null) loadOlder();
+ })
+ .on_item_click((key, cx) => transcript.click(key, cx)),
)
- // Opens at the newest row and stays there while a reply
- // streams, until the reader scrolls up. Opened at an anchor, it
- // opens at its top, the anchor's row, and keeps the reader's top
- // row in place as pages are put above and added below, until the
- // reader reaches the newest row or sends (Transcript.showing).
- .with_follow_mode(transcript.anchored ? 'normal' : 'tail')
- // Reported after the frame, however the range changed: a
- // wheel, a scrollbar drag, or rows that do not fill the view.
- .on_visible_range_change((range, shown) => {
- log(`transcript: showing ${range.start}..${range.end} of ${shown}`);
- transcript.showing(range, shown);
- if (range.start < NEAR_TOP && transcript.before !== null) loadOlder();
- })
- .on_item_click((key, cx) => transcript.click(key, cx)),
- )
- .child(Scrollbar.vertical(id).absolute().inset_0()),
- );
+ .child(Scrollbar.vertical(id).absolute().inset_0()),
+ )
+ );
}
/** One item of the transcript list, in the reading column; called from layout for each visible item. */
function transcriptItem(item, transcript, cx) {
return h_flex()
.w_full()
- .px(24)
+ .px(COLUMN_GUTTER)
.justify_center()
.child(
v_flex()
.w_full()
- .max_w(720)
+ .max_w(COLUMN_WIDTH)
.pb(item.gap)
.child(itemBody(item, transcript, cx)),
);
@@ -1911,14 +1956,16 @@ function lowSurrogate(text, index) {
/**
* Below a finished turn, as the native client's footer: how it ended when it
* did not complete, when, and the copy icon right after when the turn has
- * reply text. A click anywhere on the row copies the reply (list rows take
- * one click handler, see click).
+ * reply text; in a task's conversation, Fork at the end of the row. A click
+ * on Fork forks the task through this turn, anywhere else on the row it
+ * copies the reply (list rows take one click handler, see click).
*/
function turnFooter(item, transcript, cx) {
const m = palette(cx);
const outcome = { failed: t('failed'), aborted: t('stopped') }[item.finished.outcome] ?? null;
const copied = transcript.copied === item.key;
return h_flex()
+ .w_full()
.h(24)
.gap(4)
.items_center()
@@ -1946,6 +1993,20 @@ function turnFooter(item, transcript, cx) {
.child(icon(copied ? 'check' : 'copy', 14, copied ? m.ink : m.inkMuted))
.when(copied, (el) => el.child(text(t('copied'), 'small', m.inkMuted))),
),
+ )
+ .when(transcript.forks(), (el) =>
+ el.child(div().flex_1()).child(
+ h_flex()
+ .id(`fork-${item.turnId}`)
+ .flex_none()
+ .size(FORK_BUTTON)
+ .items_center()
+ .justify_center()
+ .rounded(6)
+ .hover((style) => style.bg(m.wash))
+ .tooltip(t('forkFromHere'))
+ .child(icon('fork', 14, m.inkMuted)),
+ ),
);
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 05/05: fix(desktop): fit the composer's row beside the Workbar in a narrow window
Posted by lu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 1423f2bbffeb35e86c7295fb651eff9c5eebc406
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sun Oct 18 04:10:26 2026 +0800
fix(desktop): fit the composer's row beside the Workbar in a narrow window
At the least window width the Workbar leaves the conversation 368 wide,
and the context control pushed Send out of the composer. Where the
conversation can be narrower than its usual least width the control
shows the ring alone, with the percentage in its tooltip, and the model's
chip shortens its name when the row is still short of room.
Generated-by: Claude Code
---
products/maka/desktop-shell/app/composer.js | 7 ++++++-
products/maka/desktop-shell/app/context.js | 11 +++++++----
products/maka/desktop-shell/app/main.js | 21 +++++++++++++++++++--
products/maka/desktop-shell/app/messages.js | 1 +
4 files changed, 33 insertions(+), 7 deletions(-)
diff --git a/products/maka/desktop-shell/app/composer.js b/products/maka/desktop-shell/app/composer.js
index cc96106221..dba3a17714 100644
--- a/products/maka/desktop-shell/app/composer.js
+++ b/products/maka/desktop-shell/app/composer.js
@@ -695,7 +695,12 @@ export function composerPane(composer, transcript, context, cx) {
cx,
),
)
- .child(modelMenu(composer, transcript, context, cx))
+ // The model's chip gives way first where the row is short of room.
+ .child(
+ div()
+ .min_w_0()
+ .child(modelMenu(composer, transcript, context, cx)),
+ )
.child(permissionMenu(composer, transcript, context, cx))
.when(context.picker !== null, (el) => el.child(context.picker))
.child(note(context, executor, cx))
diff --git a/products/maka/desktop-shell/app/context.js b/products/maka/desktop-shell/app/context.js
index acb105c951..cb28be6479 100644
--- a/products/maka/desktop-shell/app/context.js
+++ b/products/maka/desktop-shell/app/context.js
@@ -355,9 +355,11 @@ function ring(share, color, track) {
/**
* The composer's context control, before Send: the ring and the percentage
* of the limit (the token count alone without a limit), opening the
- * popover. Null while the conversation has no request to show.
+ * popover. `narrow` leaves the percentage to the tooltip where the
+ * conversation's plate can be too narrow for the composer's row. Null while
+ * the conversation has no request to show.
*/
-export function contextControl(use, cx) {
+export function contextControl(use, cx, narrow = false) {
const shown = contextUse(use.request);
if (use.transcript === null || shown === null) return null;
const m = palette(cx);
@@ -366,6 +368,7 @@ export function contextControl(use, cx) {
shown.share === null
? t('contextTokens', { count: grouped(shown.used) })
: percent(shown.share);
+ const ringOnly = narrow && shown.share !== null;
return Popover.new('context-use')
.anchor('bottom_right')
.open(use.open)
@@ -377,9 +380,9 @@ export function contextControl(use, cx) {
.gap(6)
.rounded(8)
.when(use.open, (el) => el.bg(m.selected))
- .tooltip(t('contextUseTip'))
+ .tooltip(ringOnly ? t('contextUseShare', { value: label }) : t('contextUseTip'))
.when(shown.share !== null, (el) => el.child(ring(shown.share, color, m.border)))
- .child(text(label, 'small', color)),
+ .when(!ringOnly, (el) => el.child(text(label, 'small', color))),
)
.content(
menuSurface(cx)
diff --git a/products/maka/desktop-shell/app/main.js b/products/maka/desktop-shell/app/main.js
index 6a78716cc2..407c892fca 100644
--- a/products/maka/desktop-shell/app/main.js
+++ b/products/maka/desktop-shell/app/main.js
@@ -72,6 +72,9 @@ const SIDEBAR_WIDTH = 256;
/** The narrowest the conversation's plate gets while the Workbar's divider is dragged. */
const CONVERSATION_MIN = 420;
+/** The space between the conversation's plate and the Workbar's, split between the two panels. */
+const SPLIT_GAP = 4;
+
/**
* The narrowest it gets in a window too narrow for both plates at their
* usual minimums (960 wide with the sidebar leaves them 696).
@@ -617,7 +620,7 @@ export default class MakaDesktop extends View {
withWorkbar(plate, column, cx) {
if (!this.workbar.shown()) return plate;
// Each panel holds half the gap, so the divider sits in its middle.
- const gap = 4;
+ const gap = SPLIT_GAP;
const { conversation, workbar } = this.workbarSplit(column, gap);
return h_resizable('workbar-split')
.size_full()
@@ -659,6 +662,17 @@ export default class MakaDesktop extends View {
return { shared, conversation, workbar };
}
+ /**
+ * Whether the conversation's plate can be narrower than CONVERSATION_MIN:
+ * beside the Workbar in a narrow window (see workbarSplit).
+ */
+ narrowConversation() {
+ return (
+ this.workbar.shown() &&
+ this.workbarSplit(!this.sidebarHidden, SPLIT_GAP).conversation < CONVERSATION_MIN
+ );
+ }
+
/** The plate's content for a task or a new one: header, connection strip, then the conversation. */
taskPane(el, cx) {
const transcript = this.transcript;
@@ -854,7 +868,10 @@ export default class MakaDesktop extends View {
{
folder: view.folder,
picker: view.picker,
- usage: transcript === null ? null : contextControl(this.contextUse, cx),
+ usage:
+ transcript === null
+ ? null
+ : contextControl(this.contextUse, cx, this.narrowConversation()),
// A session whose permissions were never changed still has the
// level the Host gives every new one.
defaultAccess:
diff --git a/products/maka/desktop-shell/app/messages.js b/products/maka/desktop-shell/app/messages.js
index c027146097..daccdfa44b 100644
--- a/products/maka/desktop-shell/app/messages.js
+++ b/products/maka/desktop-shell/app/messages.js
@@ -305,6 +305,7 @@ export const MESSAGES = {
// Context use and Compact, in the composer (context.js). The confirmation
// copies the TUI's (plugins/agent/agent-screen/compact.ts).
contextUseTip: ['Context use', '上下文用量', '上下文用量'],
+ contextUseShare: ['Context use: {value}', '上下文用量:{value}', '上下文用量:{value}'],
contextTokens: ['{count} tokens', '{count} tokens', '{count} tokens'],
contextUsed: [
'{used} of {limit} tokens ({percent})',
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 02/05: feat(desktop): show context use and compact in the composer
Posted by lu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit e448c897e420d1a6a9589d1d449fd399f534faf5
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sun Oct 18 03:21:42 2026 +0800
feat(desktop): show context use and compact in the composer
Before Send, the composer shows how much of the model's input limit the
conversation's newest request took (agent.context): a ring and the
percentage, in the warning color above 80% and the destructive color
above 95%, or the token count alone without a limit. It uses the
provider's count when there is one, else the sum of the Host's
estimates. The use is read when a conversation opens and whenever one of
its runs ends, a compaction included; one read per session at a time,
and an answer for a conversation no longer shown is dropped.
The ring opens a popover with the model, the use, each part of the
prepared input with its share, the message, tool call and tool counts,
a note when the request was not answered or was interrupted or when the
conversation was compacted after it, and Compact. Compact first shows
the instruction the Host would use (agent.compactionPrompt) in a field.
agent.compact sends the field's text only when it was changed to
something other than empty; otherwise it sends no prompt and the Host
uses its own. It uses the composer's model, and is off while a run goes
and in a task an executor runs. Each rejection is one sentence in the
composer's notice. When the Host does not answer, the notice says the
conversation may or may not be compacting, and Compact stays off until
the conversation shows a run or the task is opened again.
Generated-by: Claude Code
---
products/maka/desktop-shell/app/composer.js | 10 +-
products/maka/desktop-shell/app/context.js | 531 ++++++++++++++++++++++++++++
products/maka/desktop-shell/app/host.js | 9 +
products/maka/desktop-shell/app/main.js | 11 +-
products/maka/desktop-shell/app/messages.js | 102 ++++++
5 files changed, 658 insertions(+), 5 deletions(-)
diff --git a/products/maka/desktop-shell/app/composer.js b/products/maka/desktop-shell/app/composer.js
index d0fecf5eaf..24bf7f514f 100644
--- a/products/maka/desktop-shell/app/composer.js
+++ b/products/maka/desktop-shell/app/composer.js
@@ -603,11 +603,12 @@ export class Composer {
* @param {Composer} composer
* @param {import("./transcript.js").Transcript | null} transcript
* @param {{ folder: { name: string, path: string } | null, picker: object | null,
- * defaultAccess: string | null, notice: string | null, dismiss: () => void,
- * addConnection: () => void }} context
+ * usage: object | null, defaultAccess: string | null, notice: string | null,
+ * dismiss: () => void, addConnection: () => void }} context
* `folder` is where a new task starts when no task is selected, and `picker`
- * the chip that chooses it; `defaultAccess` the permission level new tasks
- * get when known; `notice` is the last error
+ * the chip that chooses it; `usage` the context use before Send (context.js),
+ * or null; `defaultAccess` the permission level new tasks get when known;
+ * `notice` is the last error
*/
export function composerPane(composer, transcript, context, cx) {
const m = palette(cx);
@@ -668,6 +669,7 @@ export function composerPane(composer, transcript, context, cx) {
.child(permissionMenu(composer, transcript, context, cx))
.when(context.picker !== null, (el) => el.child(context.picker))
.child(note(context, executor, cx))
+ .when(context.usage !== null, (el) => el.child(context.usage))
.child(
stop
? actionButton('stop', 'stop', cx)
diff --git a/products/maka/desktop-shell/app/context.js b/products/maka/desktop-shell/app/context.js
new file mode 100644
index 0000000000..acb105c951
--- /dev/null
+++ b/products/maka/desktop-shell/app/context.js
@@ -0,0 +1,531 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// The context use in the composer: how much of the model's input the
+// conversation's newest request took (`agent.context`), as a ring and a
+// percentage before Send, and a popover with what took it and Compact
+// (`agent.compact`), which first shows the instruction it will send.
+//
+// The use is read when a conversation opens and each time one of its runs
+// ends; a compaction is a run, so its end counts. main.js tells it which
+// conversation the composer serves (`follow`) whenever the window changed.
+
+import { div, PathBuilder } from 'gpui-kit';
+import { v_flex, h_flex, Popover, Textarea, TextareaState } from 'gpui-base';
+import { query, operation, log, eventOf } from './host.js';
+import { palette, typeset, text, ghostButton, menuSurface, controlButton } from './theme.js';
+import { t, tn, onLanguageChange } from './locale.js';
+
+/** Above these shares of the limit the ring turns to the warning, then the destructive color. */
+const WARN_AT = 0.8;
+const ALARM_AT = 0.95;
+
+/** The prepared input's parts (`breakdown`), in the order the popover lists them. */
+const BUCKETS = [
+ ['system', 'contextSystem'],
+ ['user', 'contextUser'],
+ ['assistant', 'contextAssistant'],
+ ['tool', 'contextTool'],
+ ['toolSchemas', 'contextToolSchemas'],
+];
+
+/** Why the Host did not start a compaction (`AgentCompactRejection`), in words. */
+const REJECTED = {
+ busy: 'compactBusy',
+ closed: 'compactClosed',
+ archived: 'compactArchived',
+ backend_unavailable: 'compactBackendUnavailable',
+ workspace_changed: 'compactWorkspaceChanged',
+};
+
+export class ContextUse {
+ /**
+ * Creates retained input state, so it belongs in the view's `init`.
+ * @param {{ changed: () => void, report: (message: string) => void }} hooks
+ * @param {import("./composer.js").Composer} composer whose model a compaction runs with
+ */
+ constructor(hooks, composer) {
+ this.hooks = hooks;
+ this.composer = composer;
+ /** The conversation the composer serves (a Transcript), or null. */
+ this.transcript = null;
+ /** How many of its runs had ended when it was last read. */
+ this.runsEnded = 0;
+ /** `agent.context`'s `request` for that conversation: its newest request, or null. */
+ this.request = null;
+ /** Sessions with a read under way, and those to read once more when it ends. */
+ this.reading = new Set();
+ this.again = new Set();
+ /** Whether the popover is open. */
+ this.open = false;
+ /**
+ * The confirmation before Compact, or null: `prompt` is the instruction
+ * the Host would use (null while it is read), which the field starts with.
+ * Left as it was, or emptied, the Host uses its own (the preference).
+ */
+ this.confirm = null;
+ this.instruction = TextareaState.new({ rows: 7, placeholder: t('compactPromptPlaceholder') });
+ this.instruction.set_soft_wrap(true);
+ onLanguageChange(() => this.instruction.set_placeholder(t('compactPromptPlaceholder')));
+ /** Whether `agent.compact` is under way. */
+ this.compacting = false;
+ /**
+ * The last Compact the Host did not answer, `{ id, transcript, runsEnded }`,
+ * or null: it may have started, so Compact waits (awaitingCompact).
+ */
+ this.unanswered = null;
+ }
+
+ /**
+ * Takes the conversation the composer serves now. Another session is read
+ * at once and its predecessor's report dropped; the same one is read again
+ * when one of its runs ended since the last look. Cheap otherwise.
+ */
+ follow(transcript) {
+ if (transcript !== this.transcript) {
+ const same = transcript !== null && transcript.id === this.transcript?.id;
+ this.transcript = transcript;
+ this.open = false;
+ this.confirm = null;
+ if (!same) this.request = null;
+ if (transcript === null) return;
+ this.runsEnded = transcript.runsEnded;
+ this.read(transcript);
+ return;
+ }
+ if (transcript === null || transcript.runsEnded === this.runsEnded) return;
+ this.runsEnded = transcript.runsEnded;
+ this.read(transcript);
+ }
+
+ /**
+ * Reads the context use of `transcript`'s session. One read per session
+ * at a time: a call while one is under way reads once more after it. An
+ * answer for a session the composer no longer serves is dropped.
+ */
+ async read(transcript) {
+ const id = transcript.id;
+ if (this.reading.has(id)) {
+ this.again.add(id);
+ return;
+ }
+ this.reading.add(id);
+ try {
+ do {
+ this.again.delete(id);
+ const report = await query(transcript.endpoint, 'context', {
+ sessionId: id,
+ through: null,
+ });
+ if (this.transcript?.id !== id) return;
+ this.request = report.request ?? null;
+ this.hooks.changed();
+ } while (this.again.has(id) && this.transcript?.id === id);
+ } catch (error) {
+ // The ring keeps what it showed; it is read again when the next run ends.
+ log(`context: reading ${id} failed: ${error.message}`);
+ } finally {
+ this.reading.delete(id);
+ this.again.delete(id);
+ }
+ }
+
+ setOpen(open) {
+ this.open = open;
+ if (!open) this.confirm = null;
+ this.hooks.changed();
+ }
+
+ /**
+ * Whether Compact can start: nothing runs in the conversation, its model
+ * is one the desktop starts, and no unanswered Compact may still start.
+ */
+ canCompact() {
+ const transcript = this.transcript;
+ return (
+ transcript !== null &&
+ transcript.ready &&
+ transcript.run === null &&
+ transcript.backend?.kind !== 'executor' &&
+ !this.compacting &&
+ !this.awaitingCompact()
+ );
+ }
+
+ /**
+ * Whether Compact waits after a Compact the Host did not answer: until the
+ * conversation shows a run start or end (a compaction is a run), or until
+ * it is opened again (a new Transcript, once it has read its rows).
+ */
+ awaitingCompact() {
+ const unanswered = this.unanswered;
+ const transcript = this.transcript;
+ if (unanswered === null || transcript === null || transcript.id !== unanswered.id) return false;
+ if (transcript !== unanswered.transcript) return !transcript.ready;
+ return transcript.run === null && transcript.runsEnded === unanswered.runsEnded;
+ }
+
+ /** Compact in the popover: shows the confirmation, with the instruction the Host would use. */
+ async askCompact() {
+ const transcript = this.transcript;
+ if (transcript === null || !this.canCompact()) return;
+ const confirm = { prompt: null };
+ this.confirm = confirm;
+ this.hooks.changed();
+ try {
+ const answer = await query(transcript.endpoint, 'compactionPrompt', {
+ sessionId: transcript.id,
+ });
+ if (this.confirm !== confirm || this.transcript !== transcript) return;
+ confirm.prompt = answer.compactionPrompt;
+ this.instruction.set_value(answer.compactionPrompt);
+ } catch (error) {
+ if (this.confirm !== confirm) return;
+ this.confirm = null;
+ this.open = false;
+ this.hooks.report(t('compactFailed', { value: error.message }));
+ }
+ this.hooks.changed();
+ }
+
+ /**
+ * The instruction Compact sends: the field's text when it was changed to
+ * some other text, else null (left as it was, or emptied: the Host uses
+ * its own, the preference).
+ */
+ promptToSend() {
+ const value = this.instruction.value();
+ return value.trim() === '' || value === this.confirm?.prompt ? null : value;
+ }
+
+ /**
+ * The confirmation's Compact: `agent.compact` with the composer's model,
+ * and the instruction only when it was changed to some other text (left as
+ * it was, or emptied, the Host uses its own). The compaction shows as a run
+ * of the conversation. The Host does not recognize a Compact sent twice, so
+ * one it did not answer is not sent again: the notice says the outcome is
+ * unknown and Compact waits until the conversation shows a run
+ * (awaitingCompact).
+ */
+ async compact() {
+ const transcript = this.transcript;
+ const confirm = this.confirm;
+ if (transcript === null || confirm?.prompt == null || !this.canCompact()) return;
+ const prompt = this.promptToSend();
+ this.compacting = true;
+ this.hooks.changed();
+ try {
+ const { model, thinkingLevel } = await this.composer.selection(transcript);
+ let result;
+ try {
+ result = await operation(transcript.endpoint, 'compact', {
+ sessionId: transcript.id,
+ model,
+ thinkingLevel,
+ prompt,
+ });
+ } catch (error) {
+ log(`context: compact of ${transcript.id} got no answer: ${error.message}`);
+ this.unanswered = { id: transcript.id, transcript, runsEnded: transcript.runsEnded };
+ this.open = false;
+ this.confirm = null;
+ this.hooks.report(t('compactUnknown'));
+ return;
+ }
+ this.open = false;
+ this.confirm = null;
+ if (result.kind === 'rejected') {
+ log(`context: compaction rejected: ${result.reason}`);
+ this.hooks.report(
+ t(REJECTED[result.reason] ?? 'compactRejected', { value: result.reason }),
+ );
+ return;
+ }
+ log(
+ `context: compaction ${result.execution.invocationId} started${prompt === null ? '' : ' with a changed instruction'}`,
+ );
+ // The compaction's facts come through the watch; this shows it running now.
+ await transcript.observeRun();
+ } catch (error) {
+ this.hooks.report(t('compactFailed', { value: error.message }));
+ } finally {
+ this.compacting = false;
+ this.hooks.changed();
+ }
+ }
+}
+
+/**
+ * What the newest request used: `{ used, limit, share, estimated }`, with
+ * the provider's count when it reported one, else the sum of the Host's
+ * estimates; `limit` and `share` are null without a known limit. Null
+ * without a request or any count.
+ */
+export function contextUse(request) {
+ if (request === null) return null;
+ const breakdown = request.breakdown ?? null;
+ const estimated = request.reportedInputTokens == null;
+ const used = estimated
+ ? breakdown === null
+ ? null
+ : estimate(breakdown)
+ : request.reportedInputTokens;
+ if (used === null) return null;
+ const limit = request.inputLimit ?? request.contextWindow ?? null;
+ return { used, limit, share: limit === null ? null : used / limit, estimated };
+}
+
+/** The Host's estimate of the whole prepared input: the sum of its parts. */
+function estimate(breakdown) {
+ return BUCKETS.reduce((sum, [bucket]) => sum + (breakdown[bucket]?.estimatedTokens ?? 0), 0);
+}
+
+/** A count of tokens with thousands separated: 200,000. */
+function grouped(count) {
+ return String(count).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
+/** A share of the limit as the ring's label: "<1%" for a little, else the rounded percentage. */
+function percent(share) {
+ if (share > 0 && share < 0.01) return '<1%';
+ return `${Math.round(share * 100)}%`;
+}
+
+/** The ring's color for a share of the limit. */
+function shareColor(share, m) {
+ if (share > ALARM_AT) return m.destructive;
+ if (share > WARN_AT) return m.warning;
+ return m.inkMuted;
+}
+
+/** A 16px ring, its track and, clockwise from the top, the arc for `share` of a turn. */
+function ring(share, color, track) {
+ const center = 8;
+ const radius = 6;
+ const top = center - radius;
+ const circle = PathBuilder.stroke(2)
+ .move_to(center, top)
+ .arc_to(radius, radius, 0, false, true, center, center + radius)
+ .arc_to(radius, radius, 0, false, true, center, top)
+ .build();
+ const turn = Math.min(1, share);
+ let arc = null;
+ if (turn >= 1) arc = circle;
+ else if (turn > 0) {
+ // A sliver stays visible however little is used.
+ const angle = Math.max(turn, 0.03) * 2 * Math.PI;
+ arc = PathBuilder.stroke(2)
+ .move_to(center, top)
+ .arc_to(
+ radius,
+ radius,
+ 0,
+ angle > Math.PI,
+ true,
+ center + radius * Math.sin(angle),
+ center - radius * Math.cos(angle),
+ )
+ .build();
+ }
+ const layer = (path, fill) => window.paint_path(path, fill).absolute().top(0).left(0).size(16);
+ return div()
+ .relative()
+ .flex_none()
+ .size(16)
+ .child(layer(circle, track))
+ .when(arc !== null, (el) => el.child(layer(arc, color)));
+}
+
+/**
+ * The composer's context control, before Send: the ring and the percentage
+ * of the limit (the token count alone without a limit), opening the
+ * popover. Null while the conversation has no request to show.
+ */
+export function contextControl(use, cx) {
+ const shown = contextUse(use.request);
+ if (use.transcript === null || shown === null) return null;
+ const m = palette(cx);
+ const color = shown.share === null ? m.inkMuted : shareColor(shown.share, m);
+ const label =
+ shown.share === null
+ ? t('contextTokens', { count: grouped(shown.used) })
+ : percent(shown.share);
+ return Popover.new('context-use')
+ .anchor('bottom_right')
+ .open(use.open)
+ .on_open_change((open) => use.setOpen(open))
+ .trigger(
+ ghostButton('context-use-button', cx)
+ .h(28)
+ .px(6)
+ .gap(6)
+ .rounded(8)
+ .when(use.open, (el) => el.bg(m.selected))
+ .tooltip(t('contextUseTip'))
+ .when(shown.share !== null, (el) => el.child(ring(shown.share, color, m.border)))
+ .child(text(label, 'small', color)),
+ )
+ .content(
+ menuSurface(cx)
+ .id('context-use-menu')
+ .w(320)
+ .p(12)
+ .gap(10)
+ .mb(8)
+ .children(
+ use.confirm === null ? details(use, shown, cx) : confirmation(use, use.confirm, cx),
+ ),
+ );
+}
+
+/** The popover's details: the model, the use, each part of the input, the counts, and Compact. */
+function details(use, shown, cx) {
+ const m = palette(cx);
+ const request = use.request;
+ const breakdown = request.breakdown ?? null;
+ const total = breakdown === null ? 0 : estimate(breakdown);
+ const usage =
+ shown.limit === null
+ ? t('contextTokens', { count: grouped(shown.used) })
+ : t('contextUsed', {
+ used: grouped(shown.used),
+ limit: grouped(shown.limit),
+ percent: percent(shown.share),
+ });
+ const counts = breakdown?.counts ?? null;
+ const note =
+ request.state === 'requested'
+ ? t('contextRequested')
+ : request.state === 'interrupted'
+ ? t('contextInterrupted')
+ : null;
+ // The report is of the newest request the model was sent; a compaction
+ // since then makes the next one smaller, which only that request shows.
+ const compacted = use.transcript.rows.some(
+ (row) => row.role === 'compaction' && eventOf(row.sequence) > request.sequence,
+ );
+ const enabled = use.canCompact();
+ const rows = [
+ v_flex()
+ .gap(2)
+ .child(text(request.modelId, 'label', m.ink).truncate())
+ .child(
+ text(shown.estimated ? `${usage} · ${t('contextEstimated')}` : usage, 'small', m.inkMuted),
+ ),
+ ];
+ if (breakdown !== null) {
+ rows.push(
+ v_flex()
+ .gap(4)
+ .children(
+ BUCKETS.map(([bucket, label]) => {
+ const tokens = breakdown[bucket]?.estimatedTokens ?? 0;
+ const width = total > 0 ? Math.max(0, Math.min(100, (tokens / total) * 100)) : 0;
+ return h_flex()
+ .gap(8)
+ .items_center()
+ .child(text(t(label), 'small', m.ink).w(124).flex_none().truncate())
+ .child(
+ div()
+ .flex_1()
+ .h(4)
+ .rounded(2)
+ .bg(m.wash)
+ .child(
+ div()
+ .h_full()
+ .w(`${width.toFixed(1)}%`)
+ .rounded(2)
+ .bg(m.inkMuted),
+ ),
+ )
+ .child(text(grouped(tokens), 'small', m.inkMuted).w(56).flex_none().text_right());
+ }),
+ ),
+ );
+ }
+ if (counts !== null) {
+ rows.push(
+ text(
+ [
+ tn(counts.messages, 'contextMessagesOne', 'contextMessagesOther'),
+ tn(counts.toolCalls, 'contextToolCallsOne', 'contextToolCallsOther'),
+ tn(counts.tools, 'contextToolsOne', 'contextToolsOther'),
+ ].join(' · '),
+ 'small',
+ m.inkMuted,
+ ),
+ );
+ }
+ if (note !== null) rows.push(text(note, 'small', m.warning));
+ if (compacted) rows.push(text(t('contextCompactedSince'), 'small', m.inkMuted));
+ rows.push(
+ h_flex()
+ .justify_end()
+ .child(
+ controlButton('context-compact', t('compact'), 'outline', !enabled, cx)
+ .tooltip(
+ enabled
+ ? t('compactTip')
+ : use.awaitingCompact()
+ ? t('compactAwaiting')
+ : t('compactUnavailable'),
+ )
+ .on_click(() => use.askCompact()),
+ ),
+ );
+ return rows;
+}
+
+/** The confirmation: what Compact does, the instruction it sends, Cancel and Compact. */
+function confirmation(use, confirm, cx) {
+ const m = palette(cx);
+ const loading = confirm.prompt === null;
+ const ready = !loading && use.canCompact();
+ return [
+ v_flex()
+ .gap(2)
+ .child(text(t('compactTitle'), 'strong', m.ink))
+ .child(text(t('compactHelp'), 'small', m.inkMuted)),
+ loading
+ ? text(t('compactLoading'), 'small', m.inkMuted)
+ : typeset(Textarea.new(use.instruction), 'small')
+ .w_full()
+ .px(8)
+ .py(6)
+ .rounded(8)
+ .border_1()
+ .border_color(m.borderStrong)
+ .bg(m.plate)
+ .text_color(m.ink),
+ h_flex()
+ .gap(8)
+ .justify_end()
+ .child(
+ controlButton('compact-cancel', t('cancel'), 'outline', false, cx).on_click(() =>
+ use.setOpen(false),
+ ),
+ )
+ .child(
+ controlButton('compact-confirm', t('compactConfirm'), 'primary', !ready, cx).on_click(() =>
+ use.compact(),
+ ),
+ ),
+ ];
+}
diff --git a/products/maka/desktop-shell/app/host.js b/products/maka/desktop-shell/app/host.js
index 3a1bc0af77..efbd29a911 100644
--- a/products/maka/desktop-shell/app/host.js
+++ b/products/maka/desktop-shell/app/host.js
@@ -82,6 +82,15 @@ export async function readModels(search = '') {
return null;
}
+/**
+ * The raw event a transcript row belongs to: a row's sequence is its event's
+ * sequence times 256 plus the row's place in the event
+ * (platform/event-log/src/transcript/model.rs).
+ */
+export function eventOf(rowSequence) {
+ return Math.floor(rowSequence / 256);
+}
+
/**
* Reads one `history` page of an Agent endpoint (`agent`, or WorkHub's
* `coordinator`), asking again with the same fence and position while the
diff --git a/products/maka/desktop-shell/app/main.js b/products/maka/desktop-shell/app/main.js
index 98bf142284..b526d36670 100644
--- a/products/maka/desktop-shell/app/main.js
+++ b/products/maka/desktop-shell/app/main.js
@@ -38,6 +38,7 @@ import { query, operation, log, setDebug } from './host.js';
import { SessionCatalog, SidebarState, sidebar } from './sessions.js';
import { Transcript, transcriptPane } from './transcript.js';
import { Composer, composerPane } from './composer.js';
+import { ContextUse, contextControl } from './context.js';
import { interactionCard } from './interactions.js';
import { Settings, settingsNav, settingsPage } from './settings.js';
import { Directories, folderPicker } from './directories.js';
@@ -130,6 +131,8 @@ export default class MakaDesktop extends View {
return folder === null ? Promise.resolve(null) : this.newSession(folder);
},
);
+ // The composer's context use follows the conversation the composer serves.
+ this.contextUse = new ContextUse(hooks, this.composer);
// A model added or chosen in Settings is what the composer sends with next,
// and the subagents Settings reads or saves are what WorkHub's hint goes by.
this.settings = new Settings({
@@ -255,9 +258,14 @@ export default class MakaDesktop extends View {
return this.transcript;
}
- /** Tells the Workbar what the window shows now; cheap when nothing it follows changed. */
+ /**
+ * Tells the Workbar what the window shows now, and the composer's context
+ * use which conversation the composer serves; cheap when nothing they
+ * follow changed.
+ */
syncWorkbar() {
this.workbar.follow(this.workbarTarget());
+ this.contextUse.follow(this.current());
}
/** Records a move from the current place, for Back. */
@@ -704,6 +712,7 @@ export default class MakaDesktop extends View {
{
folder: view.folder,
picker: view.picker,
+ usage: transcript === null ? null : contextControl(this.contextUse, cx),
// A session whose permissions were never changed still has the
// level the Host gives every new one.
defaultAccess:
diff --git a/products/maka/desktop-shell/app/messages.js b/products/maka/desktop-shell/app/messages.js
index c39da4ab8f..0b737a81ed 100644
--- a/products/maka/desktop-shell/app/messages.js
+++ b/products/maka/desktop-shell/app/messages.js
@@ -219,6 +219,108 @@ export const MESSAGES = {
attachmentClosed: ['the Host is closing', 'Host 正在关闭', 'Host 正在關閉'],
attachmentArchived: ['the task is archived', '任务已归档', '任務已封存'],
+ // Context use and Compact, in the composer (context.js). The confirmation
+ // copies the TUI's (plugins/agent/agent-screen/compact.ts).
+ contextUseTip: ['Context use', '上下文用量', '上下文用量'],
+ contextTokens: ['{count} tokens', '{count} tokens', '{count} tokens'],
+ contextUsed: [
+ '{used} of {limit} tokens ({percent})',
+ '已用 {used} / {limit} tokens({percent})',
+ '已用 {used} / {limit} tokens({percent})',
+ ],
+ contextEstimated: ['estimated', '估算', '估算'],
+ contextSystem: ['System', '系统', '系統'],
+ contextUser: ['Messages you sent', '你发送的消息', '你傳送的訊息'],
+ contextAssistant: ['Replies', '回复', '回覆'],
+ contextTool: ['Tool results', '工具结果', '工具結果'],
+ contextToolSchemas: ['Tool definitions', '工具定义', '工具定義'],
+ contextMessagesOne: ['{count} message', '{count} 条消息', '{count} 則訊息'],
+ contextMessagesOther: ['{count} messages', '{count} 条消息', '{count} 則訊息'],
+ contextToolCallsOne: ['{count} tool call', '{count} 次工具调用', '{count} 次工具呼叫'],
+ contextToolCallsOther: ['{count} tool calls', '{count} 次工具调用', '{count} 次工具呼叫'],
+ contextToolsOne: ['{count} tool', '{count} 个工具', '{count} 個工具'],
+ contextToolsOther: ['{count} tools', '{count} 个工具', '{count} 個工具'],
+ contextRequested: [
+ 'These numbers are from a request the model has not answered yet.',
+ '这些数字来自模型尚未回复的请求。',
+ '這些數字來自模型尚未回覆的請求。',
+ ],
+ contextInterrupted: [
+ 'These numbers are from a request that was interrupted.',
+ '这些数字来自一次被中断的请求。',
+ '這些數字來自一次被中斷的請求。',
+ ],
+ contextCompactedSince: [
+ 'The conversation was compacted after this request. The next request will show the new size.',
+ '此请求之后对话已被压缩,下一次请求会显示新的用量。',
+ '此請求之後對話已被壓縮,下一次請求會顯示新的用量。',
+ ],
+ compact: ['Compact', '压缩', '壓縮'],
+ compactTip: [
+ 'Summarize the conversation so far to free up context',
+ '总结目前的对话,以腾出上下文空间',
+ '總結目前的對話,以騰出上下文空間',
+ ],
+ compactUnavailable: [
+ 'Compact is available while nothing runs in this task',
+ '任务中没有运行时才能压缩',
+ '任務中沒有執行時才能壓縮',
+ ],
+ compactTitle: ['Compact context', '压缩上下文', '壓縮上下文'],
+ compactHelp: [
+ 'This prompt applies to this compression only.',
+ '此提示词仅用于本次压缩。',
+ '此提示詞僅用於本次壓縮。',
+ ],
+ compactLoading: ['Loading prompt…', '正在加载提示词…', '正在載入提示詞…'],
+ compactConfirm: ['Compact', '开始压缩', '開始壓縮'],
+ compactFailed: ['Compact: {value}', '压缩失败:{value}', '壓縮失敗:{value}'],
+ compactRejected: [
+ 'The Host did not start the compaction ({value}).',
+ 'Host 没有开始压缩({value})。',
+ 'Host 沒有開始壓縮({value})。',
+ ],
+ compactBusy: [
+ 'Something is running in this task. Compact when it ends.',
+ '这个任务正在运行,结束后再压缩。',
+ '這個任務正在執行,結束後再壓縮。',
+ ],
+ compactClosed: [
+ 'The Host is closing, so the conversation cannot be compacted.',
+ 'Host 正在关闭,无法压缩对话。',
+ 'Host 正在關閉,無法壓縮對話。',
+ ],
+ compactUnknown: [
+ 'The Host did not answer, so the conversation may or may not be compacting. Compact comes back once this task shows a run, or after you open the task again.',
+ 'Host 没有回应,对话可能正在压缩,也可能没有。任务显示出运行后,或重新打开任务后,才能再次压缩。',
+ 'Host 沒有回應,對話可能正在壓縮,也可能沒有。任務顯示出執行後,或重新開啟任務後,才能再次壓縮。',
+ ],
+ compactAwaiting: [
+ 'Waiting for this task to show whether the last Compact started',
+ '正在等待任务显示上次压缩是否已开始',
+ '正在等待任務顯示上次壓縮是否已開始',
+ ],
+ compactPromptPlaceholder: [
+ 'Leave empty to use the default prompt',
+ '留空则使用默认提示词',
+ '留空則使用預設提示詞',
+ ],
+ compactArchived: [
+ 'This task is archived, so it cannot be compacted.',
+ '这个任务已归档,无法压缩。',
+ '這個任務已封存,無法壓縮。',
+ ],
+ compactBackendUnavailable: [
+ 'The model for this task is not available, so it cannot be compacted.',
+ '这个任务的模型不可用,无法压缩。',
+ '這個任務的模型無法使用,無法壓縮。',
+ ],
+ compactWorkspaceChanged: [
+ "The task's folder changed, so it cannot be compacted.",
+ '任务的文件夹已变化,无法压缩。',
+ '任務的資料夾已變化,無法壓縮。',
+ ],
+
// Folder picker (directories.js)
choose: ['Choose', '选择', '選擇'],
chooseFolderFailed: [
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 04/05: feat(desktop): find in a conversation
Posted by lu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-conversation-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 1bd28011d7b39a03e05c55159f7cd4c7fcd1f2b6
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sun Oct 18 03:57:29 2026 +0800
feat(desktop): find in a conversation
Cmd+F opens a find bar at the top of the conversation the window shows,
a task's or WorkHub's. It scans the conversation with agent.search at
the transcript's fence, 250 ms after the field last changed, batch after
batch up to 1000 matches; the count grows with "+" until the scan ends.
Once it ends the newest match is selected. Enter and Shift+Enter go to
the next and previous match and wrap around. Match case and Match whole
word restart the scan. Escape closes the bar and gives the keyboard back
to the composer when it had it.
The selected match's row is tinted, and the text it matched is marked in
sent messages. A match in thinking tints the thinking row, and a match
in a failure the run recorded twice tints the one item that shows both.
A loaded row is shown at the top of the list in place; a row not loaded
opens the conversation again at it, as a Search passage does. That page
is read from the first row of the row's event, which includes rows
without text such as a tool's result, and the list is drawn from the
row. A tool's item is keyed by its call, so a result read before its
call keeps its place at the top when the call is read in above it.
Showing another conversation closes the bar and drops its scan.
Generated-by: Claude Code
---
products/maka/desktop-shell/app/composer.js | 48 ++-
products/maka/desktop-shell/app/find.js | 480 ++++++++++++++++++++++++++
products/maka/desktop-shell/app/main.js | 48 ++-
products/maka/desktop-shell/app/messages.js | 18 +
products/maka/desktop-shell/app/search.js | 5 +-
products/maka/desktop-shell/app/theme.js | 6 +
products/maka/desktop-shell/app/transcript.js | 150 ++++++--
products/maka/desktop-shell/app/workhub.js | 6 +-
8 files changed, 722 insertions(+), 39 deletions(-)
diff --git a/products/maka/desktop-shell/app/composer.js b/products/maka/desktop-shell/app/composer.js
index 24bf7f514f..cc96106221 100644
--- a/products/maka/desktop-shell/app/composer.js
+++ b/products/maka/desktop-shell/app/composer.js
@@ -37,6 +37,7 @@ import {
menuLabel,
menuSeparator,
controlButton,
+ focusInput,
} from './theme.js';
import { t, onLanguageChange } from './locale.js';
@@ -66,15 +67,17 @@ const REJECTIONS = {
export class Composer {
/**
- * Creates retained input state, so it belongs in the view's `init`.
+ * Creates retained input state and a focus handle, so it belongs in the
+ * view's `init`, whose context it keeps for focusing the draft.
* @param {{ changed: () => void, report: (message: string) => void }} hooks
* @param {() => import("./transcript.js").Transcript | null} target the session Enter sends to
* @param {() => Promise<import("./transcript.js").Transcript | null>} start starts a session
* when none is selected, and resolves with it
*/
- constructor(hooks, target, start) {
+ constructor(hooks, target, start, cx) {
this.hooks = hooks;
this.start = start;
+ this.cx = cx;
this.draft = TextareaState.new({ placeholder: t('composerPlaceholder'), rows: 1 });
this.draft.set_auto_grow(1, 8);
// The placeholder follows a change of language; the draft lives as long as the app.
@@ -94,6 +97,16 @@ export class Composer {
this.draft.on('submit', (event) => {
if (!event.shift) this.send(target());
});
+ /** Whether the draft has the keyboard, as its focus events say (Find gives it back). */
+ this.focused = false;
+ this.draft.on('focus', () => {
+ this.focused = true;
+ });
+ this.draft.on('blur', () => {
+ this.focused = false;
+ });
+ /** Around the draft: what the keyboard is moved from to reach it (focusDraft). */
+ this.draftFocus = cx.focus_handle();
/** The default model's choice, or the first offered one, for sessions without their own. */
this.model = null;
/** That model's name, or null when there is none (the footer then says so). */
@@ -133,6 +146,18 @@ export class Composer {
this.choosing = false;
}
+ /** Gives the draft the keyboard, as Find does when it closes. */
+ focusDraft() {
+ this.cx.spawn(async (cx) => {
+ await focusInput(
+ this.draftFocus,
+ () => this.focused,
+ () => true,
+ cx,
+ );
+ });
+ }
+
/** The files attached to the draft for `transcript`, or for a new task. */
attachments(transcript) {
return this.attached.get(transcript?.id ?? '') ?? [];
@@ -641,14 +666,19 @@ export function composerPane(composer, transcript, context, cx) {
.p(12)
.gap(6)
.child(
- typeset(Textarea.new(composer.draft), 'body')
+ div()
.w_full()
- .px(8)
- .py(4)
- .bg('#00000000')
- .border_0()
- .text_color(m.ink)
- .disabled(inactive),
+ .track_focus(composer.draftFocus)
+ .child(
+ typeset(Textarea.new(composer.draft), 'body')
+ .w_full()
+ .px(8)
+ .py(4)
+ .bg('#00000000')
+ .border_0()
+ .text_color(m.ink)
+ .disabled(inactive),
+ ),
)
.when(files.length > 0, (el) =>
el.child(attachmentRow(composer, transcript, files, cx)),
diff --git a/products/maka/desktop-shell/app/find.js b/products/maka/desktop-shell/app/find.js
new file mode 100644
index 0000000000..ab1296bf0d
--- /dev/null
+++ b/products/maka/desktop-shell/app/find.js
@@ -0,0 +1,480 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Find in the conversation the window shows (⌘F): a bar at the top of the
+// transcript with a field, the count, Previous and Next, Match case, Match
+// whole word, and Close. The Host's `agent.search` scans the conversation's
+// history at a fixed fence in batches of at most 16 matches, oldest first;
+// the bar asks for batch after batch in the background, up to MAX_MATCHES,
+// and the count grows as they come. A match is a row (and a field of it),
+// not each place in it. Once the scan ends the newest match is selected;
+// Enter goes to the next, newer match and Shift+Enter to the one before,
+// wrapping around once the scan has ended. The selected match's row is
+// shown with a tint, and in a sent message, which is plain text, the text
+// it matched is marked (markedPlain). Replies are markdown, which marks
+// inserted into it could change, so they, tools and thinking get the tint
+// only.
+//
+// The bar belongs to one conversation: main.js tells it which one the
+// window shows (`follow`), and showing another closes it.
+
+import { div } from 'gpui-kit';
+import { h_flex, v_flex, InputState } from 'gpui-base';
+import { query, log } from './host.js';
+import {
+ palette,
+ typeset,
+ text,
+ icon,
+ iconButton,
+ ghostButton,
+ textField,
+ focusInput,
+ escapeHtml,
+} from './theme.js';
+import { t, onLanguageChange } from './locale.js';
+
+/** How long the bar waits after the field last changed before it scans. */
+const PAUSE_MS = 250;
+/** The most matches one scan collects; the count then says "1000+". */
+const MAX_MATCHES = 1000;
+/** The longest query the Host takes, in UTF-8 bytes. */
+const MAX_QUERY_BYTES = 512;
+/** How long to wait before asking again while the Host prepares the scan, and how often. */
+const PREPARING_MS = 100;
+const PREPARING_TRIES = 100;
+
+function utf8Length(value) {
+ let size = 0;
+ for (const point of value) {
+ const code = point.codePointAt(0);
+ size += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : code <= 0xffff ? 3 : 4;
+ }
+ return size;
+}
+
+/** The tint of the selected match's row, lighter than the marks in it (MATCH_FILL). */
+export const FOUND_ROW = { light: '#FFCE2F1F', dark: '#FFCE2F14' };
+
+/** A Unicode word character as the Host's whole-word search counts them. */
+const WORD = '[\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}]';
+
+/**
+ * A RegExp that finds `query` in text as `agent.search` matches it: the
+ * literal text, in any case unless `caseSensitive` (simple case folding,
+ * as the Host folds), and with no word character next to it when
+ * `wholeWord`. Null when the runtime cannot build it.
+ */
+function findPattern(query, caseSensitive, wholeWord) {
+ const literal = query.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
+ const source = wholeWord ? `(?<!${WORD})${literal}(?!${WORD})` : literal;
+ try {
+ return new RegExp(source, caseSensitive ? 'gu' : 'giu');
+ } catch {
+ return null;
+ }
+}
+
+/** `value` as escaped HTML with every match of `pattern` marked on `fill`. */
+export function markedPlain(value, pattern, fill) {
+ let html = '';
+ let last = 0;
+ pattern.lastIndex = 0;
+ for (const match of value.matchAll(pattern)) {
+ if (match[0] === '') continue;
+ html += `${escapeHtml(value.slice(last, match.index))}<mark color="${fill}">${escapeHtml(match[0])}</mark>`;
+ last = match.index + match[0].length;
+ }
+ return html + escapeHtml(value.slice(last));
+}
+
+export class Find {
+ /**
+ * Creates retained input state and a focus handle, so it belongs in the
+ * view's `init`, whose context it keeps for the pause and the Host calls.
+ * @param {{ changed: () => void, report: (message: string) => void,
+ * reveal: (transcript: object, sequence: number) => void,
+ * giveBack: (toComposer: boolean) => void }} hooks
+ * `reveal` shows the row at `sequence` (its `field`) in the transcript, and
+ * `giveBack` returns the keyboard when the bar closes: to the composer
+ * when it had it before the bar opened, else to the window
+ */
+ constructor(hooks, cx) {
+ this.hooks = hooks;
+ this.cx = cx;
+ /** Whether the bar shows, over the conversation `transcript`. */
+ this.open = false;
+ this.transcript = null;
+ this.field = InputState.new({ placeholder: t('findPlaceholder') });
+ onLanguageChange(() => this.field.set_placeholder(t('findPlaceholder')));
+ this.field.on('change', () => {
+ if (this.field.value() !== this.scan?.query) this.restart(PAUSE_MS);
+ });
+ // Enter and Shift+Enter; Escape comes through the row around the field (key).
+ this.field.on('submit', (event) => this.step(event?.shift ? -1 : 1));
+ this.field.on('focus', () => {
+ this.focused = true;
+ });
+ this.field.on('blur', () => {
+ this.focused = false;
+ });
+ /** Whether the field has the keyboard, as its focus events say. */
+ this.focused = false;
+ /** On the row around the field: what the keyboard is moved from to reach it (focusInput). */
+ this.fieldFocus = cx.focus_handle();
+ this.focusing = 0;
+ this.caseSensitive = false;
+ this.wholeWord = false;
+ /** Whether the composer had the keyboard when the bar opened. */
+ this.fromComposer = false;
+ /** Bumped by every scan and by closing: the batches of an earlier scan are dropped. */
+ this.serial = 0;
+ /**
+ * The scan under way or done, or null: `{ serial, query, caseSensitive,
+ * wholeWord, through, pattern, matches, done, capped, failed }`.
+ */
+ this.scan = null;
+ /** The selected match's index in `scan.matches`, or -1. */
+ this.index = -1;
+ /** The most matches a scan collects (a driver lowers it), and the Host calls made. */
+ this.max = MAX_MATCHES;
+ this.stats = { calls: 0 };
+ }
+
+ /**
+ * ⌘F over `transcript`: opens the bar, or gives its field the keyboard
+ * again, with the field's text selected. `composerFocused` says where the
+ * keyboard goes back to on Escape.
+ */
+ show(transcript, composerFocused) {
+ if (!this.open || this.transcript?.id !== transcript.id) {
+ this.open = true;
+ this.transcript = transcript;
+ this.fromComposer = composerFocused;
+ log(`find: open over ${transcript.id}`);
+ if (this.field.value() !== '') this.restart(0);
+ this.hooks.changed();
+ }
+ this.focusField();
+ }
+
+ /** Closes the bar and drops its scan and selection; `giveBack` returns the keyboard (Escape, Close). */
+ hide(giveBack) {
+ if (!this.open) return;
+ this.open = false;
+ this.serial += 1;
+ this.scan = null;
+ this.index = -1;
+ if (this.transcript !== null) this.transcript.found = null;
+ this.transcript = null;
+ log('find: closed');
+ this.hooks.changed();
+ if (giveBack) this.hooks.giveBack(this.fromComposer);
+ }
+
+ /**
+ * Takes the conversation the window shows now. Another conversation, or
+ * none, closes the bar; the same one opened again (at a match's row) gets
+ * the selected match's tint.
+ */
+ follow(transcript) {
+ if (!this.open || transcript === this.transcript) return;
+ if (transcript === null || transcript.id !== this.transcript.id) {
+ this.hide(false);
+ return;
+ }
+ this.transcript = transcript;
+ transcript.found = this.found();
+ }
+
+ focusField() {
+ const attempt = ++this.focusing;
+ this.cx.spawn(async (cx) => {
+ const current = await focusInput(
+ this.fieldFocus,
+ () => this.focused,
+ () => this.open && attempt === this.focusing,
+ cx,
+ );
+ if (current) this.field.set_selected_range({ start: 0, end: this.field.value().length });
+ });
+ }
+
+ /** Keys the field passes on: Escape closes the bar. */
+ key(event) {
+ if (event.keystroke === 'escape') this.hide(true);
+ }
+
+ toggleCase() {
+ this.caseSensitive = !this.caseSensitive;
+ this.restart(0);
+ }
+
+ toggleWord() {
+ this.wholeWord = !this.wholeWord;
+ this.restart(0);
+ }
+
+ /**
+ * Starts a scan of the field's text after `pause` ms, or now, at the
+ * newest fence the conversation knows then. The Host has no cancel: each scan is
+ * numbered and the batches of any but the latest are dropped.
+ */
+ restart(pause) {
+ const serial = ++this.serial;
+ this.index = -1;
+ if (this.transcript !== null) this.transcript.found = null;
+ const transcript = this.transcript;
+ const query = this.field.value();
+ const tooLong = utf8Length(query) > MAX_QUERY_BYTES;
+ if (!this.open || transcript === null || query === '' || tooLong) {
+ this.scan = tooLong ? { serial, query, tooLong: true, matches: [], done: true } : null;
+ this.hooks.changed();
+ return;
+ }
+ const scan = {
+ serial,
+ query,
+ caseSensitive: this.caseSensitive,
+ wholeWord: this.wholeWord,
+ through: 0,
+ pattern: findPattern(query, this.caseSensitive, this.wholeWord),
+ matches: [],
+ done: false,
+ capped: false,
+ failed: null,
+ };
+ this.scan = scan;
+ this.hooks.changed();
+ this.cx.spawn(async (cx) => {
+ if (pause > 0) await cx.sleep(pause);
+ // The fence is the newest the transcript knows, once it has read its first page.
+ while (!transcript.ready && serial === this.serial) await cx.sleep(50);
+ if (serial !== this.serial) return;
+ scan.through = Math.max(transcript.latestKnown, transcript.olderFence);
+ try {
+ await this.run(scan, transcript, cx);
+ } catch (error) {
+ if (serial !== this.serial) return;
+ log(`find #${serial} failed: ${error.message}`);
+ scan.failed = error.message;
+ scan.done = true;
+ this.hooks.report(t('findFailed', { value: error.message }));
+ }
+ this.hooks.changed();
+ });
+ }
+
+ /** Asks for batch after batch of `scan` until the Host says it ended, the cap, or a newer scan. */
+ async run(scan, transcript, cx) {
+ let after = 0;
+ let preparing = 0;
+ const started = Date.now();
+ for (;;) {
+ this.stats.calls += 1;
+ const page = await query(transcript.endpoint, 'search', {
+ sessionId: transcript.id,
+ through: scan.through,
+ after,
+ query: scan.query,
+ caseSensitive: scan.caseSensitive,
+ wholeWord: scan.wholeWord,
+ includeInternal: false,
+ });
+ if (scan.serial !== this.serial) return;
+ if (page.kind === 'preparing') {
+ preparing += 1;
+ if (preparing > PREPARING_TRIES) throw new Error(t('findNotReady'));
+ await cx.sleep(PREPARING_MS);
+ if (scan.serial !== this.serial) return;
+ continue;
+ }
+ const room = this.max - scan.matches.length;
+ scan.matches = [...scan.matches, ...page.matches.slice(0, room)];
+ if (
+ page.matches.length > room ||
+ (scan.matches.length === this.max && page.nextAfter !== null)
+ ) {
+ scan.capped = true;
+ }
+ if (scan.capped || page.nextAfter === null) break;
+ after = page.nextAfter;
+ this.hooks.changed();
+ }
+ scan.done = true;
+ log(
+ `find #${scan.serial}: ${scan.matches.length}${scan.capped ? '+' : ''} match(es) in ${Date.now() - started} ms`,
+ );
+ // The first selection: the newest match, once the scan has ended.
+ if (this.index < 0 && scan.matches.length > 0) this.select(scan.matches.length - 1);
+ }
+
+ /**
+ * Enter (`direction` 1, the next, newer match) and Shift+Enter (-1, the
+ * one before). With none selected yet, the newest found so far. Past
+ * either end it wraps around once the scan has ended, and stays otherwise.
+ */
+ step(direction) {
+ const scan = this.scan;
+ const count = scan?.matches.length ?? 0;
+ if (count === 0) return;
+ let index = this.index < 0 ? count - 1 : this.index + direction;
+ if (index < 0) index = scan.done ? count - 1 : 0;
+ if (index >= count) index = scan.done ? 0 : count - 1;
+ this.select(index);
+ }
+
+ /** Selects match `index`: its row gets the tint and is shown. */
+ select(index) {
+ const match = this.scan?.matches[index];
+ if (match === undefined || this.transcript === null) return;
+ this.index = index;
+ this.transcript.found = this.found();
+ log(`find: match ${index + 1} of ${this.scan.matches.length} at row ${match.cursor.sequence}`);
+ this.hooks.reveal(this.transcript, match.cursor.sequence, match.field);
+ this.hooks.changed();
+ }
+
+ /** What the transcript shows of the selected match: `{ sequence, field, pattern }`, or null. */
+ found() {
+ const match = this.index < 0 ? undefined : this.scan?.matches[this.index];
+ if (match === undefined) return null;
+ return { sequence: match.cursor.sequence, field: match.field, pattern: this.scan.pattern };
+ }
+
+ /** The count beside the field: "3 of 12", "12+" while the scan goes on, "No results", or null. */
+ count() {
+ const scan = this.scan;
+ if (scan === null) return null;
+ if (scan.tooLong) return t('findTooLong');
+ if (scan.failed !== null) return t('findError');
+ const found = scan.matches.length;
+ if (scan.done && found === 0) return t('findNoResults');
+ if (!scan.done && found === 0) return '…';
+ const total = `${found}${scan.done && !scan.capped ? '' : '+'}`;
+ return this.index < 0 ? total : t('findCount', { index: this.index + 1, count: total });
+ }
+}
+
+/**
+ * The bar, at the top of the conversation in its reading column: the field
+ * with the search glyph, the count, Previous and Next, Match case ("Aa"),
+ * Match whole word ("ab", underlined) and Close.
+ */
+export function findBar(find, cx) {
+ const m = palette(cx);
+ const count = find.count();
+ const any = (find.scan?.matches.length ?? 0) > 0;
+ const toggle = (id, label, on, tip, underline, act) =>
+ typeset(ghostButton(id, cx), 'smallLabel')
+ .h(28)
+ .min_w(28)
+ .px(4)
+ .justify_center()
+ .rounded(8)
+ .text_color(on ? m.ink : m.inkMuted)
+ .when(on, (el) => el.bg(m.selected))
+ .tooltip(tip)
+ .on_click(act)
+ .child(underline ? div().underline().child(label) : label);
+ return h_flex()
+ .flex_none()
+ .w_full()
+ .px(24)
+ .py(8)
+ .justify_center()
+ .child(
+ h_flex()
+ .w_full()
+ .max_w(720)
+ .p(4)
+ .gap(2)
+ .items_center()
+ .rounded(12)
+ .border_1()
+ .border_color(m.border)
+ .bg(m.plate)
+ .child(
+ div()
+ .id('find-field')
+ .relative()
+ .flex_1()
+ .min_w_0()
+ .h(28)
+ .track_focus(find.fieldFocus)
+ .on_key_down((event) => find.key(event))
+ .child(textField(find.field, cx).h(28).pl(30).border_0())
+ .child(icon('search', 14, m.inkMuted).absolute().left(10).top(7)),
+ )
+ .when(count !== null, (el) =>
+ el.child(
+ text(count, 'small', find.scan?.failed ? m.destructive : m.inkMuted)
+ .flex_none()
+ .px(6),
+ ),
+ )
+ .child(
+ iconButton('find-previous', 'chevron-up', cx)
+ .disabled(!any)
+ .tooltip(t('findPrevious'))
+ .on_click(() => find.step(-1)),
+ )
+ .child(
+ iconButton('find-next', 'chevron-down', cx)
+ .disabled(!any)
+ .tooltip(t('findNext'))
+ .on_click(() => find.step(1)),
+ )
+ .child(div().w(1).h(16).mx(2).bg(m.border))
+ .child(
+ toggle('find-case', 'Aa', find.caseSensitive, t('findMatchCase'), false, () =>
+ find.toggleCase(),
+ ),
+ )
+ .child(
+ toggle('find-word', 'ab', find.wholeWord, t('findWholeWord'), true, () =>
+ find.toggleWord(),
+ ),
+ )
+ .child(
+ iconButton('find-close', 'close', cx)
+ .tooltip(t('findClose'))
+ .on_click(() => find.hide(true)),
+ ),
+ );
+}
+
+/**
+ * Whether a transcript item shows the row at `sequence`: a tool's result
+ * shows with its call, and a failure with the same reason recorded before
+ * it (`also`). A row's thinking and its body share the sequence; `field`
+ * (a match's source field, or null for either) says which: `thinking` is
+ * the thinking item, any other field the row's other item.
+ */
+export function holdsRow(item, sequence, field = null) {
+ if (item.kind === 'thinking') {
+ return item.row.sequence === sequence && (field === null || field === 'thinking');
+ }
+ if (field === 'thinking' || item.kind === 'footer') return false;
+ return (
+ item.row?.sequence === sequence ||
+ item.result?.sequence === sequence ||
+ (item.also?.includes(sequence) ?? false)
+ );
+}
diff --git a/products/maka/desktop-shell/app/main.js b/products/maka/desktop-shell/app/main.js
index 830dfce43c..6a78716cc2 100644
--- a/products/maka/desktop-shell/app/main.js
+++ b/products/maka/desktop-shell/app/main.js
@@ -39,6 +39,7 @@ import { SessionCatalog, SidebarState, sidebar } from './sessions.js';
import { Transcript, transcriptPane } from './transcript.js';
import { Composer, composerPane } from './composer.js';
import { ContextUse, contextControl } from './context.js';
+import { Find, findBar } from './find.js';
import { interactionCard } from './interactions.js';
import { Settings, settingsNav, settingsPage } from './settings.js';
import { Directories, folderPicker } from './directories.js';
@@ -89,6 +90,7 @@ const SHORTCUTS = [
{ keystroke: 'secondary-]', action: 'maka.forward' },
{ keystroke: 'secondary-,', action: 'maka.settings' },
{ keystroke: 'secondary-shift-f', action: 'maka.search' },
+ { keystroke: 'secondary-f', action: 'maka.find' },
{ keystroke: 'secondary-.', action: 'maka.stop' },
{ keystroke: 'f2', action: 'maka.rename-task' },
{ keystroke: 'ctrl-shift-g', action: 'maka.toggle-changes' },
@@ -140,9 +142,24 @@ export default class MakaDesktop extends View {
const folder = this.startFolder();
return folder === null ? Promise.resolve(null) : this.newSession(folder);
},
+ cx,
);
// The composer's context use follows the conversation the composer serves.
this.contextUse = new ContextUse(hooks, this.composer);
+ // Find in the conversation the window shows: a row it selects is shown
+ // in place when loaded, else the conversation opens again at it.
+ this.find = new Find(
+ {
+ changed: hooks.changed,
+ report,
+ reveal: (transcript, sequence, field) => this.reveal(transcript, sequence, field),
+ giveBack: (toComposer) => {
+ if (toComposer) this.composer.focusDraft();
+ else this.rootFocus.focus();
+ },
+ },
+ cx,
+ );
// A model added or chosen in Settings is what the composer sends with next,
// and the subagents Settings reads or saves are what WorkHub's hint goes by.
this.settings = new Settings({
@@ -277,13 +294,34 @@ export default class MakaDesktop extends View {
}
/**
- * Tells the Workbar what the window shows now, and the composer's context
- * use which conversation the composer serves; cheap when nothing they
- * follow changed.
+ * Tells the Workbar and Find what the window shows now, and the
+ * composer's context use which conversation the composer serves; cheap
+ * when nothing they follow changed.
*/
syncWorkbar() {
this.workbar.follow(this.workbarTarget());
this.contextUse.follow(this.current());
+ this.find.follow(this.workbarTarget());
+ }
+
+ /** ⌘F: Find over the conversation the window shows, if it shows one. */
+ startFind() {
+ const transcript = this.workbarTarget();
+ if (transcript === null) return;
+ this.find.show(transcript, this.composer.focused);
+ }
+
+ /**
+ * Shows Find's row at `sequence` (its `field`): in place when the
+ * transcript has it loaded, else by opening the conversation again at that
+ * row, as a Search passage opens its task (Find follows the conversation
+ * it opens).
+ */
+ reveal(transcript, sequence, field) {
+ if (transcript.reveal(sequence, field)) return;
+ log(`find: row ${sequence} is not loaded; opening the conversation at it`);
+ if (transcript.endpoint === 'coordinator') this.workhub.attach(transcript.session, sequence);
+ else this.select(transcript.session, false, sequence);
}
/** Records a move from the current place, for Back. */
@@ -519,6 +557,7 @@ export default class MakaDesktop extends View {
.on_action('maka.forward', () => this.go(1))
.on_action('maka.settings', () => this.settings.show())
.on_action('maka.search', () => this.startSearch())
+ .on_action('maka.find', () => this.startFind())
.on_action('maka.rename-task', () => this.renameSelected())
.on_action('maka.toggle-changes', () => this.workbar.toggle('changes'))
.on_action('maka.toggle-files', () => this.workbar.toggle('files'))
@@ -797,7 +836,10 @@ export default class MakaDesktop extends View {
const card = transcript ? interactionCard(transcript.interactions, cx) : null;
const failed = transcript !== null && card === null ? transcript.failedTurn() : null;
const bar = card === null && failed === null ? view.bar : null;
+ const finding =
+ this.find.open && transcript !== null && this.find.transcript?.id === transcript.id;
return el
+ .when(finding, (el) => el.child(findBar(this.find, cx)))
.when(transcript === null, (el) => el.child(view.empty))
.when(transcript !== null, (el) =>
el.child(transcriptPane(transcript, () => transcript.loadOlder(), cx, view.hint)),
diff --git a/products/maka/desktop-shell/app/messages.js b/products/maka/desktop-shell/app/messages.js
index d6c3e90676..c027146097 100644
--- a/products/maka/desktop-shell/app/messages.js
+++ b/products/maka/desktop-shell/app/messages.js
@@ -1299,6 +1299,24 @@ export const MESSAGES = {
searchFailed: ['Couldn’t search: {value}', '搜索失败:{value}', '搜尋失敗:{value}'],
searchClear: ['Clear', '清除', '清除'],
+ // Find in the conversation shown (find.js, ⌘F)
+ findPlaceholder: ['Find in this conversation', '在此对话中查找', '在此對話中尋找'],
+ findCount: ['{index} of {count}', '第 {index} 个,共 {count} 个', '第 {index} 個,共 {count} 個'],
+ findNoResults: ['No results', '无结果', '沒有結果'],
+ findTooLong: ['Too long', '过长', '過長'],
+ findError: ['Failed', '失败', '失敗'],
+ findPrevious: ['Previous match (⇧↩)', '上一个(⇧↩)', '上一個(⇧↩)'],
+ findNext: ['Next match (↩)', '下一个(↩)', '下一個(↩)'],
+ findMatchCase: ['Match case', '区分大小写', '區分大小寫'],
+ findWholeWord: ['Match whole word', '全字匹配', '全字相符'],
+ findClose: ['Close (Esc)', '关闭(Esc)', '關閉(Esc)'],
+ findFailed: ['Find failed: {value}', '查找失败:{value}', '尋找失敗:{value}'],
+ findNotReady: [
+ 'the Host did not finish preparing the search',
+ 'Host 没有完成搜索的准备',
+ 'Host 沒有完成搜尋的準備',
+ ],
+
// WorkHub: setup and the conversation (workhub.js, main.js)
workhubChat: ['Chat', '对话', '對話'],
workhubTasks: ['Tasks', '任务', '任務'],
diff --git a/products/maka/desktop-shell/app/search.js b/products/maka/desktop-shell/app/search.js
index 8741b4f273..2187d848a6 100644
--- a/products/maka/desktop-shell/app/search.js
+++ b/products/maka/desktop-shell/app/search.js
@@ -46,6 +46,7 @@ import {
compactAge,
focusInput,
escapeHtml,
+ MATCH_FILL,
} from './theme.js';
import { t, onLanguageChange } from './locale.js';
@@ -61,8 +62,6 @@ const EXCERPT_CHARS = 220;
const BEFORE_MATCH = 60;
/** How far a cut moves to fall between two words, in characters. */
const WORD_SLACK = 16;
-/** The fill behind a match: the native client's find match (maka-gpui crates/shared/src/theme.rs). */
-const MARK = { light: '#FFCE2F59', dark: '#FFCE2F38' };
/** The words of `value` as the Host is asked for them: split on whitespace, as the TUI splits them. */
function termsOf(value) {
@@ -610,7 +609,7 @@ function resultItems(answer, byId, fill) {
*/
function resultsList(search, answer, sessions, stale, cx) {
const byId = new Map(sessions.map((session) => [session.id, session]));
- const all = resultItems(answer, byId, cx.theme().is_dark ? MARK.dark : MARK.light);
+ const all = resultItems(answer, byId, cx.theme().is_dark ? MATCH_FILL.dark : MATCH_FILL.light);
const from = search.restoring
? Math.max(
0,
diff --git a/products/maka/desktop-shell/app/theme.js b/products/maka/desktop-shell/app/theme.js
index a2938cbf92..645fa50453 100644
--- a/products/maka/desktop-shell/app/theme.js
+++ b/products/maka/desktop-shell/app/theme.js
@@ -414,6 +414,12 @@ export function escapeHtml(value) {
.replace(/'/g, ''');
}
+/**
+ * The fill behind a match that Search or Find marks in text: the native
+ * client's find match (maka-gpui crates/shared/src/theme.rs).
+ */
+export const MATCH_FILL = { light: '#FFCE2F59', dark: '#FFCE2F38' };
+
/** A 32px text field: plate fill, the strong border, the accent ring when focused. */
export function textField(state, cx) {
const m = palette(cx);
diff --git a/products/maka/desktop-shell/app/transcript.js b/products/maka/desktop-shell/app/transcript.js
index 1a3218c7f6..1373e615eb 100644
--- a/products/maka/desktop-shell/app/transcript.js
+++ b/products/maka/desktop-shell/app/transcript.js
@@ -45,8 +45,9 @@
import { div, list } from 'gpui-kit';
import { v_flex, h_flex, TextView, Scrollbar } from 'gpui-base';
-import { query, subscribe, next, close, log, readHistory, readSource } from './host.js';
+import { query, subscribe, next, close, log, readHistory, readSource, eventOf } from './host.js';
import { Interactions } from './interactions.js';
+import { markedPlain, holdsRow, FOUND_ROW } from './find.js';
import {
palette,
typeset,
@@ -58,6 +59,7 @@ import {
fileChip,
escapeHtml,
MONTHS,
+ MATCH_FILL,
} from './theme.js';
import { t, tn, language } from './locale.js';
@@ -256,6 +258,18 @@ export class Transcript {
* rest of the footer by it (see onForkButton).
*/
this.press = null;
+ /**
+ * Find's selected match, `{ sequence, field, pattern }`: its row is
+ * tinted, and in a sent message the text `pattern` finds is marked. Null
+ * without one.
+ */
+ this.found = null;
+ /**
+ * The row Find last showed at the top of the list, `{ sequence, drawn }`,
+ * and how many times it did (the list's id counts them; see reveal).
+ */
+ this.jump = null;
+ this.jumps = 0;
/** The list items last built from the rows (see displayItems). */
this.view = null;
/**
@@ -336,6 +350,8 @@ export class Transcript {
`(${this.stats.tailCalls} history call(s), fence ${fence}, older ${this.before ? 'available' : 'none'}` +
`${anchored === null ? '' : `, at row ${this.anchor}`})`,
);
+ // A first page that starts before the anchor's row (see readAnchor) is drawn from that row.
+ if (anchored !== null && this.rows[0]?.sequence !== this.anchor) this.reveal(this.anchor);
this.hooks.changed();
// Facts after the observed fence arrive on the first pages; any that
// change the transcript read history after the tail just loaded.
@@ -348,12 +364,16 @@ export class Transcript {
}
/**
- * The history page that starts at the anchor's row, read at `fence` as the
- * TUI reads it: after the row's start. Null when it cannot be read or has
- * nothing, and the transcript then opens at the newest row as usual.
+ * The history page that starts at the anchor's row, read at `fence`: the
+ * page from the first row of the anchor's event (an `event` position,
+ * which takes rows without text in this view, such as a tool's call or
+ * result, as a cursor at their start does not). When the event has rows
+ * before the anchor's, open draws the list from the anchor's row. Null
+ * when it cannot be read or has nothing, and the transcript then opens at
+ * the newest row as usual.
*/
async readAnchor(fence) {
- const position = { kind: 'after', cursor: { sequence: this.anchor, offset: 0, field: 'body' } };
+ const position = { kind: 'event', sequence: eventOf(this.anchor) };
try {
const { page, calls } = await readHistory(this.historyInput(fence, position), this.endpoint);
this.stats.tailCalls += calls;
@@ -832,6 +852,29 @@ export class Transcript {
this.hooks.changed();
}
+ /**
+ * Shows the row at `sequence` (its `field`, when given; see holdsRow) at
+ * the top of the list, for Find, when it is loaded, and answers whether it
+ * was. A list cannot be scrolled to an item, but a new list opens at its
+ * first item: a list with a new id is drawn from the row's item for one
+ * frame, then whole, and keeps that item at its top (transcriptPane). It
+ * stays there while rows are added, as at an anchor, until the reader
+ * reaches the newest row again. A loaded row that no item shows leaves the
+ * list as it is.
+ */
+ reveal(sequence, field = null) {
+ if (!this.ready || !this.rows.some((row) => row.sequence === sequence)) return false;
+ if (!displayItems(this).some((item) => holdsRow(item, sequence, field))) {
+ log(`transcript "${this.session.title}": no item shows row ${sequence}`);
+ return true;
+ }
+ this.jumps += 1;
+ this.jump = { sequence, field, drawn: false };
+ this.anchored = true;
+ this.hooks.changed();
+ return true;
+ }
+
/** Whether turn footers offer Fork: a task's conversation, not WorkHub's. */
forks() {
return this.endpoint === 'agent' && typeof this.hooks.fork === 'function';
@@ -1020,23 +1063,38 @@ function displayItems(transcript) {
// Drawn with its call.
} else if (row.role === 'tool_call' || row.role === 'tool_result') {
const result = row.role === 'tool_call' ? (results.get(row.sequence) ?? null) : row;
+ // Keyed by its call's sequence, whether the call is loaded or not: a
+ // result read before its call (a transcript opened at the result) keeps
+ // its key, and so its place at the top of the list, when the call is
+ // read in above it.
+ const call = row.role === 'tool_call' ? row.sequence : row.tool?.call?.sequence;
+ const key = call === undefined ? row.key : `tool/${call}`;
items.push({
- key: row.key,
+ key,
kind: 'tool',
row,
result,
- open: transcript.expanded.has(row.key),
+ open: transcript.expanded.has(key),
});
} else if (row.role === 'thinking') {
items.push({ key: row.key, kind: 'thinking', row, open: transcript.expanded.has(row.key) });
} else if (row.role === 'failure') {
- // A run's interruption and its end can both record the same reason.
+ // A run's interruption and its end can both record the same reason:
+ // one item shows both, keyed by the later row so that its key stays
+ // when the earlier one is read in after it. `also` lists the rows it
+ // stands for besides its own (holdsRow).
const previous = items.at(-1);
const repeated =
previous?.kind === 'failure' &&
previous.row.turnId === row.turnId &&
previous.row.text === row.text;
- if (!repeated) items.push({ key: row.key, kind: 'failure', row });
+ const item = { key: row.key, kind: 'failure', row };
+ if (repeated) {
+ item.also = [previous.row.sequence, ...(previous.also ?? [])];
+ items[items.length - 1] = item;
+ } else {
+ items.push(item);
+ }
} else if (row.role === 'compaction') {
// As in the TUI, a checkpoint shows only once it was adopted.
if (row.compaction !== null) items.push({ key: row.key, kind: 'compaction', row });
@@ -1103,9 +1161,19 @@ export function transcriptPane(transcript, loadOlder, cx, empty = null) {
const m = palette(cx);
// One snapshot for this render; the list's callbacks run during later
// layouts and must agree with the count given here.
- const items = displayItems(transcript);
+ const all = displayItems(transcript);
+ // After Find showed a row: the items from it on for one frame (reveal).
+ const jump = transcript.jump;
+ const from =
+ jump === null || jump.drawn
+ ? 0
+ : Math.max(
+ 0,
+ all.findIndex((item) => holdsRow(item, jump.sequence, jump.field)),
+ );
+ const items = from > 0 ? all.slice(from) : all;
const hasRows = transcript.rows.length + transcript.pending.length + transcript.live.length > 0;
- const id = `transcript-${transcript.id}`;
+ const id = `transcript-${transcript.id}${transcript.jumps > 0 ? `-${transcript.jumps}` : ''}`;
return (
v_flex()
.id(`${id}-area`)
@@ -1141,10 +1209,17 @@ export function transcriptPane(transcript, loadOlder, cx, empty = null) {
.with_follow_mode(transcript.anchored ? 'normal' : 'tail')
// Reported after the frame, however the range changed: a
// wheel, a scrollbar drag, or rows that do not fill the view.
+ // The range is of the items drawn, which start at `from`.
.on_visible_range_change((range, shown) => {
- log(`transcript: showing ${range.start}..${range.end} of ${shown}`);
- transcript.showing(range, shown);
- if (range.start < NEAR_TOP && transcript.before !== null) loadOlder();
+ const start = range.start + from;
+ const end = range.end + from;
+ log(`transcript: showing ${start}..${end} of ${shown + from}`);
+ if (jump !== null && !jump.drawn) {
+ jump.drawn = true;
+ if (from > 0) transcript.hooks.changed();
+ }
+ transcript.showing({ start, end }, shown + from);
+ if (start < NEAR_TOP && transcript.before !== null) loadOlder();
})
.on_item_click((key, cx) => transcript.click(key, cx)),
)
@@ -1155,6 +1230,14 @@ export function transcriptPane(transcript, loadOlder, cx, empty = null) {
/** One item of the transcript list, in the reading column; called from layout for each visible item. */
function transcriptItem(item, transcript, cx) {
+ const found = transcript.found;
+ const hit = found !== null && holdsRow(item, found.sequence, found.field);
+ const body = itemBody(item, transcript, cx, hit ? found.pattern : null);
+ const dark = cx.theme().is_dark;
+ // Find's match: the row tinted, reaching 8 past the column on each side
+ // and 8 above and below the row (16 for a sent message, which has 16
+ // above it already), taken from the space after it where there is some.
+ const below = item.kind === 'user' ? 16 : 8;
return h_flex()
.w_full()
.px(COLUMN_GUTTER)
@@ -1163,18 +1246,39 @@ function transcriptItem(item, transcript, cx) {
v_flex()
.w_full()
.max_w(COLUMN_WIDTH)
- .pb(item.gap)
- .child(itemBody(item, transcript, cx)),
+ .pb(hit ? Math.max(0, item.gap - below) : item.gap)
+ .child(
+ hit
+ ? div()
+ .mx(-8)
+ .px(8)
+ .when(item.kind !== 'user', (el) => el.pt(8))
+ .pb(below)
+ .rounded(8)
+ .bg(dark ? FOUND_ROW.dark : FOUND_ROW.light)
+ .child(body)
+ : body,
+ ),
);
}
-function itemBody(item, transcript, cx) {
+/**
+ * An item's content; `pattern`, when given, finds the text to mark in a sent
+ * message (Find). Replies are markdown, which marks inserted into it can
+ * change, so they get only the row's tint.
+ */
+function itemBody(item, transcript, cx, pattern = null) {
const m = palette(cx);
+ const fill = cx.theme().is_dark ? MATCH_FILL.dark : MATCH_FILL.light;
switch (item.kind) {
case 'history':
return historyRow(item.state, transcript, cx);
case 'user':
- return userMessage(item.row, cx);
+ return userMessage(
+ item.row,
+ cx,
+ pattern === null ? null : (own) => markedPlain(own, pattern, fill),
+ );
case 'assistant':
return markdownText(`md-${item.key}`, item.row.text, cx);
case 'thinking':
@@ -1225,9 +1329,10 @@ function plainHtml(value) {
/**
* A message the user sent: its files right-aligned above the bubble with its
* text, which can be selected and copied as a reply's can. A message of files
- * alone has no bubble.
+ * alone has no bubble. `marked`, when given, makes the text's HTML with
+ * Find's matches marked.
*/
-function userMessage(row, cx) {
+function userMessage(row, cx, marked = null) {
const m = palette(cx);
const files = row.attachments ?? [];
const own = ownText(row);
@@ -1257,7 +1362,10 @@ function userMessage(row, cx) {
.bg(m.bubble)
.text_color(m.ink)
.child(
- TextView.html(`sent-${row.key}`, plainHtml(own)).text_style({
+ TextView.html(
+ marked === null ? `sent-${row.key}` : `sent-${row.key}-found`,
+ marked === null ? plainHtml(own) : `<pre>\n${marked(own)}</pre>`,
+ ).text_style({
paragraph_gap: 0,
foreground: m.ink,
}),
diff --git a/products/maka/desktop-shell/app/workhub.js b/products/maka/desktop-shell/app/workhub.js
index 204c8de8f6..288406a035 100644
--- a/products/maka/desktop-shell/app/workhub.js
+++ b/products/maka/desktop-shell/app/workhub.js
@@ -231,8 +231,8 @@ export class WorkHub {
}
/** Opens the conversation of `session` while WorkHub shows. */
- attach(session) {
- if (!this.open || this.transcript?.id === session.id) return;
+ attach(session, anchor = null) {
+ if (!this.open || (this.transcript?.id === session.id && anchor === null)) return;
this.transcript?.close();
// A notice that a task ended names it and shows it in the Tasks tab.
const hooks = {
@@ -240,7 +240,7 @@ export class WorkHub {
taskTitle: (taskId) => this.titleOf(taskId),
openTask: (taskId, worker) => this.openTask(taskId, worker),
};
- const transcript = new Transcript(session, hooks, 'coordinator');
+ const transcript = new Transcript(session, hooks, 'coordinator', { anchor });
this.transcript = transcript;
transcript.open();
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org