Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(threads): take back a just-sent message with Escape for 15 seconds

rubenluetke10-beep13c4114f9cd9
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
index 8433f5fbdc..f1b44f2d2a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
@@ -4,7 +4,7 @@ import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip"
import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";
import { ComposerTypeahead } from "@/components/agentchat/ComposerTypeahead";
import { DictationButton } from "@/components/agentchat/DictationButton";
-import { runningTurn, type QuestionState, type Timeline, type ToolBlock, type TurnItem } from "@/components/agentchat/reduce";
+import { runningTurn, type QuestionState, type Timeline, type ToolBlock, type TurnItem, type UserItem } from "@/components/agentchat/reduce";
import { releaseHeldFiles, useChatAttachments, type HeldFiles } from "@/components/agentchat/useChatAttachments";
import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
import { useComposerTypeahead } from "@/components/agentchat/useComposerTypeahead";
@@ -14,6 +14,7 @@ import { joinProviderOptions, type ComposerDraft, type ProviderOption } from "@/
import { cn } from "@/lib/utils";
import { effortLadder, snapEffort } from "@/lib/effortLadder";
import { AccessPicker, AgentModelPicker, EffortPicker, modelsOf } from "./ThreadPickers";
+import { useRecalledMessages } from "./recalledMessages";
import { rememberSeat, rememberedSeat, threadAgents, useThreadChatStore } from "./threadModel";
/** A message typed while the agent was still working, sent when it is free. */
@@ -29,31 +30,47 @@ const drafts = new Map<string, string>();
const queues = new Map<string, QueuedMessage[]>();
/**
- * The message sent last, with its files, so Escape can take it back while the
- * agent has not started on it. Module-level: a thread's first message swaps
- * the empty-thread composer for the timeline one.
+ * The message sent last, with its files and when it went, so Escape can take
+ * it back. Module-level: a thread's first message swaps the empty-thread
+ * composer for the timeline one.
*/
-let lastSent: { text: string; files: HeldFiles } | null = null;
+interface SentMessage { text: string; files: HeldFiles; sentMs: number }
+let lastSent: SentMessage | null = null;
-function keepSent(next: { text: string; files: HeldFiles } | null): void {
+/** How long after sending Escape still takes a message back once the agent started thinking. */
+export const RECALL_WINDOW_MS = 15_000;
+
+function keepSent(next: SentMessage | null): void {
if (lastSent && lastSent.files !== next?.files) releaseHeldFiles(lastSent.files);
lastSent = next;
}
/**
- * True while the running turn answers `sent` and shows no work yet: no
- * reasoning, no tool call, no words. The message right before the turn must be
- * the one sent, so a queued follow-up or another thread's turn never hands back
- * the wrong text.
+ * The user item `sent` became, when Escape may still take it back: it is the
+ * newest message, and nothing after it is more than the reply still running.
+ * While that reply shows no work the message comes back however long the
+ * agent takes to connect; once it reasons or writes, only inside
+ * RECALL_WINDOW_MS; once it ran a tool, never — that work may have touched
+ * files. Matching the text keeps a queued follow-up or another thread from
+ * handing back the wrong message.
*/
-function untouchedReply(timeline: Timeline, sent: { text: string; files: HeldFiles }): boolean {
+function recallableItem(timeline: Timeline, sent: SentMessage, now: number): UserItem | null {
+ let index = timeline.items.length - 1;
+ while (index >= 0 && timeline.items[index].type !== "user") index -= 1;
+ const asked = timeline.items[index];
+ if (!asked || asked.type !== "user") return null;
+ if (sent.text ? asked.text.trim() !== sent.text : !sameFiles(asked, sent.files)) return null;
+ const after = timeline.items.slice(index + 1);
const turn = runningTurn(timeline);
- if (!turn || !turn.blocks.every((block) => block.kind === "text" && !block.text.trim())) return false;
- const index = timeline.items.indexOf(turn);
- const asked = timeline.items.slice(0, index).reverse().find((item) => item.type === "user");
- if (!asked || asked.type !== "user") return false;
- if (sent.text) return asked.text.trim() === sent.text;
- const names = sent.files.attachments.map((item) => item.name).sort().join("|");
+ if (after.some((item) => item !== turn)) return null;
+ if (!turn) return asked;
+ if (turn.blocks.some((block) => block.kind === "tool")) return null;
+ const working = turn.blocks.some((block) => block.kind !== "text" || block.text.trim());
+ return !working || now - sent.sentMs <= RECALL_WINDOW_MS ? asked : null;
+}
+
+function sameFiles(asked: UserItem, files: HeldFiles): boolean {
+ const names = files.attachments.map((item) => item.name).sort().join("|");
return names !== "" && asked.attachments.map((item) => item.name).sort().join("|") === names;
}
@@ -406,7 +423,7 @@ export function ThreadComposer({
setQueue((current) => [...current, { id: ++queueId.current, text, attachments }]);
return;
}
- keepSent({ text, files: held });
+ keepSent({ text, files: held, sentMs: Date.now() });
const sent = await dispatch(text, attachments);
if (!sent && !useThreadChatStore.getState().activeSessionId) {
// Nothing was created: give the words back instead of losing them.
@@ -414,14 +431,16 @@ export function ThreadComposer({
}
};
- // Escape before the agent started on the message stops the turn and puts the
- // message, files included, back into the box to edit and send again.
+ // Escape soon after sending stops the turn, takes the message out of the
+ // thread and puts it, files included, back into the box to edit and send again.
const recall = useRef<() => boolean>(() => false);
recall.current = () => {
- if (!lastSent || !untouchedReply(timeline, lastSent)) return false;
+ const asked = lastSent && recallableItem(timeline, lastSent, Date.now());
+ if (!lastSent || !asked) return false;
const { text, files: held } = lastSent;
lastSent = null;
setPaused(true);
+ if (activeSessionId) useRecalledMessages.getState().hide(activeSessionId, asked.id);
void useThreadChatStore.getState().cancel();
const current = drafts.get(threadKey) ?? "";
setValue(current.trim() ? `${text}\n${current}` : text);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadRecall.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadRecall.test.tsx
index 1f8a5b1b12..fff4d38018 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadRecall.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadRecall.test.tsx
@@ -148,9 +148,65 @@ describe("Escape takes back a message the agent has not started on", () => {
expect(screen.getByTestId("chat-attachment-shot.png")).toBeTruthy();
});
- it("leaves the message alone once the agent started thinking", async () => {
+ it("takes the message out of the thread, and it stays out once the stopped turn closes", async () => {
+ await sendWithShot("fix the login");
+ expect(screen.getAllByTestId("thread-user-message")).toHaveLength(2);
+
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+ feed([["turn_finished", { turn_id: "t1", status: "cancelled", duration_ms: 10 }]]);
+
+ expect(screen.getAllByTestId("thread-user-message")).toHaveLength(1);
+ expect(screen.getAllByTestId("thread-turn")).toHaveLength(1);
+ });
+
+ it("still takes it back while the agent thinks inside the first seconds", async () => {
+ const box = await sendWithShot("fix the login");
+ feed([["reasoning_started", { turn_id: "t1" }], ["text_delta", { turn_id: "t1", text: "Looking" }]]);
+
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+
+ expect(api.cancelAgentChatTurn).toHaveBeenCalledWith("s1");
+ expect(box.value).toBe("fix the login");
+ expect(screen.getByTestId("chat-attachment-shot.png")).toBeTruthy();
+ });
+
+ it("takes it back before the agent's turn even started", async () => {
+ useIdeThreadsStore.setState({ selection: { projectId: "p1", sessionId: "s1" } });
+ api.fetchAgentChatSessions.mockResolvedValue([sessionRow()]);
+ render(<ThreadView onScreen />);
+ await waitFor(() => expect(useThreadChatStore.getState().activeSessionId).toBe("s1"));
+ feed([["user_message", { text: "earlier" }], ["turn_started", { turn_id: "t0", provider: "claude-api", model: "", effort: "high", runner: "claude-cli" }],
+ ["turn_finished", { turn_id: "t0", status: "done", duration_ms: 10 }]]);
+ const box = screen.getByTestId("thread-composer-input") as HTMLTextAreaElement;
+ fireEvent.change(box, { target: { value: "rename it" } });
+ await act(async () => { fireEvent.keyDown(box, { key: "Enter" }); });
+ await waitFor(() => expect(api.sendAgentChatMessage).toHaveBeenCalled());
+ feed([["user_message", { text: "rename it" }]]);
+
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+
+ expect(box.value).toBe("rename it");
+ expect(screen.getAllByTestId("thread-user-message")).toHaveLength(1);
+ });
+
+ it("leaves the message alone once the agent thought past the window", async () => {
+ const now = Date.now();
+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);
const box = await sendWithShot("fix the login");
feed([["reasoning_started", { turn_id: "t1" }]]);
+ clock.mockReturnValue(now + 16_000);
+
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+ clock.mockRestore();
+
+ expect(api.cancelAgentChatTurn).not.toHaveBeenCalled();
+ expect(box.value).toBe("");
+ expect(screen.getAllByTestId("thread-user-message")).toHaveLength(2);
+ });
+
+ it("leaves the message alone once the agent ran a tool", async () => {
+ const box = await sendWithShot("fix the login");
+ feed([["tool_call", { turn_id: "t1", call_id: "c1", name: "Bash", input: { command: "ls" } }]]);
await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
index a3010518af..4130a07627 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
@@ -8,6 +8,7 @@ import { ThreadBranchBar, type ThreadCheckout } from "./ThreadBranchBar";
import { ThreadComposer } from "./ThreadComposer";
import { ThreadMenuItem, ThreadPopover } from "./ThreadPopover";
import { ThreadTimeline } from "./ThreadTimeline";
+import { useRecalledMessages, withoutRecalled } from "./recalledMessages";
import { projectIdFor, rememberedSeat, useThreadChatStore } from "./threadModel";
/**
@@ -30,6 +31,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
const activeSessionId = useThreadChatStore((state) => state.activeSessionId);
const activeSession = useThreadChatStore((state) => state.activeSession);
const timeline = useThreadChatStore((state) => state.timeline);
+ const recalled = useRecalledMessages((state) => (activeSessionId ? state.bySession[activeSessionId] : undefined));
const draft = useThreadChatStore((state) => state.draft);
const catalog = useThreadChatStore((state) => state.catalog);
const lastError = useThreadChatStore((state) => state.lastError);
@@ -188,7 +190,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
</div>
</div>
: <>
- <ThreadTimeline items={timeline.items} sessionId={selection.sessionId} bottomInset={composerHeight} folder={folder} />
+ <ThreadTimeline items={withoutRecalled(timeline.items, recalled)} sessionId={selection.sessionId} bottomInset={composerHeight} folder={folder} />
<div ref={composerBox} className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-background from-70% to-transparent px-5 pb-4 pt-6">
<div className="pointer-events-auto">
<ThreadComposer threadKey={threadKey} prepareDraft={prepareDraft} autoFocusNonce={focusNonce} strip={strip} onScreen={onScreen} />
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/recalledMessages.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/recalledMessages.ts
new file mode 100644
index 0000000000..d3429cc412
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/recalledMessages.ts
@@ -0,0 +1,60 @@
+import { create } from "zustand";
+import type { TimelineItem } from "@/components/agentchat/reduce";
+
+/**
+ * Messages the person took back with Escape. The transcript keeps them (the
+ * event log is append-only), so the thread hides each one, and the stopped
+ * turn that answered it, by the user item's id — stable across reloads,
+ * because it comes from the event's seq.
+ */
+
+const STORAGE_KEY = "jarvis.threads.recalled";
+/** Enough for any thread; the oldest sessions drop out first. */
+const SESSION_LIMIT = 200;
+
+type Recalled = Record<string, string[]>;
+
+function load(): Recalled {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ const parsed: unknown = raw ? JSON.parse(raw) : {};
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Recalled : {};
+ } catch {
+ // Unreadable or blocked storage: nothing is hidden, the thread still works.
+ return {};
+ }
+}
+
+function save(next: Recalled): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ // Storage full or blocked: the message stays hidden until the next reload only.
+ }
+}
+
+export const useRecalledMessages = create<{ bySession: Recalled; hide: (sessionId: string, userItemId: string) => void }>((set, get) => ({
+ bySession: load(),
+ hide: (sessionId, userItemId) => {
+ const current = get().bySession;
+ const ids = current[sessionId] ?? [];
+ if (ids.includes(userItemId)) return;
+ const { [sessionId]: _drop, ...rest } = current;
+ const entries = Object.entries({ ...rest, [sessionId]: [...ids, userItemId] });
+ const next = Object.fromEntries(entries.slice(-SESSION_LIMIT));
+ save(next);
+ set({ bySession: next });
+ },
+}));
+
+/** The timeline without the taken-back messages and whatever answered them. */
+export function withoutRecalled<T extends Pick<TimelineItem, "type" | "id">>(items: T[], hidden: readonly string[] | undefined): T[] {
+ if (!hidden?.length) return items;
+ const out: T[] = [];
+ let skipping = false;
+ for (const item of items) {
+ if (item.type === "user") skipping = hidden.includes(item.id);
+ if (!skipping) out.push(item);
+ }
+ return out;
+}