Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): manage bot memory (#46)

Leo708149f900d5
diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsx
index 262468e16..bc15a61b8 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx
@@ -7,6 +7,7 @@ import {
} from "@t3tools/contracts";
import {
Cancel01Icon,
+ Brain02Icon,
Edit02Icon,
PanelRightCloseIcon,
PanelRightIcon,
@@ -43,6 +44,7 @@ import { AvatarPickerDialog } from "./AvatarPickerDialog";
import { BotAvatarView } from "./BotAvatarView";
import { BotModelPicker } from "./BotModelPicker";
import { BotUsageSection } from "./BotUsageSection";
+import { BotMemorySheet } from "./BotMemorySheet";
import {
BOT_SANDBOX_OPTIONS,
botSandboxChoice,
@@ -51,6 +53,7 @@ import {
} from "./botSandbox";
import { BotToolsSheet, buildBotToolItems } from "./BotToolsSheet";
import type { Bot } from "./types";
+import type { ScopedThreadRef } from "@t3tools/contracts";
const NO_ENVIRONMENT = "" as EnvironmentId;
@@ -90,9 +93,11 @@ export interface BotProfileUpdate {
function BotProfileEditor({
bot,
onSave,
+ threadRef,
}: {
readonly bot: Bot;
readonly onSave?: (input: BotProfileUpdate) => Promise<boolean>;
+ readonly threadRef: ScopedThreadRef | null;
}) {
const providers = useAtomValue(primaryServerProvidersAtom);
const environmentId = usePrimaryEnvironmentId();
@@ -106,6 +111,7 @@ function BotProfileEditor({
const [saved, setSaved] = useState(false);
const [engineChanged, setEngineChanged] = useState(false);
const [toolsOpen, setToolsOpen] = useState(false);
+ const [memoryOpen, setMemoryOpen] = useState(false);
const [sandbox, setSandbox] = useState<BotSandboxChoice>(() => botSandboxChoice(bot.sandbox));
const [voiceEnabled, setVoiceEnabled] = useState(bot.voiceEnabled);
const [disabledMcpServerIds, setDisabledMcpServerIds] = useState<readonly McpServerId[]>(
@@ -254,6 +260,21 @@ function BotProfileEditor({
<BotUsageSection environmentId={environmentId} botId={bot.id} />
+ <div className="space-y-2">
+ <div className="text-sm font-medium">Memory</div>
+ <button
+ type="button"
+ aria-label="Manage bot memory"
+ disabled={!threadRef}
+ onClick={() => setMemoryOpen(true)}
+ className="flex min-h-10 w-full items-center gap-3 rounded-lg border border-border bg-muted/20 px-3 text-left outline-none transition-colors enabled:hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
+ >
+ <AppIcon className="size-4 shrink-0 text-muted-foreground" icon={Brain02Icon} />
+ <span className="min-w-0 flex-1 text-sm">Facts and history</span>
+ <span className="text-xs text-muted-foreground">Manage</span>
+ </button>
+ </div>
+
<div className="space-y-2">
<div className="text-sm font-medium">Sandbox</div>
<Select
@@ -348,6 +369,7 @@ function BotProfileEditor({
markChanged();
}}
/>
+ <BotMemorySheet open={memoryOpen} onOpenChange={setMemoryOpen} threadRef={threadRef} />
</div>
);
}
@@ -355,9 +377,11 @@ function BotProfileEditor({
export function BotDetailsPanel({
bot,
onSaveBot,
+ threadRef = null,
}: {
readonly bot: Bot;
readonly onSaveBot?: (input: BotProfileUpdate) => Promise<boolean>;
+ readonly threadRef?: ScopedThreadRef | null;
}) {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const [panelState, dispatchPanel] = useReducer(reduceBotDetailsPanelState, {
@@ -396,7 +420,11 @@ export function BotDetailsPanel({
<h2 className="text-sm font-medium">Settings</h2>
<div className="absolute right-3 flex items-center">{closeButton}</div>
</header>
- <BotProfileEditor bot={bot} {...(onSaveBot ? { onSave: onSaveBot } : {})} />
+ <BotProfileEditor
+ bot={bot}
+ threadRef={threadRef}
+ {...(onSaveBot ? { onSave: onSaveBot } : {})}
+ />
</>
);
diff --git a/apps/web/src/components/roster/BotMemorySheet.test.tsx b/apps/web/src/components/roster/BotMemorySheet.test.tsx
new file mode 100644
index 000000000..c65ecfc74
--- /dev/null
+++ b/apps/web/src/components/roster/BotMemorySheet.test.tsx
@@ -0,0 +1,204 @@
+// @effect-diagnostics nodeBuiltinImport:off - The component contract reads its source.
+import * as NodeFS from "node:fs";
+
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import {
+ AkeruMemoryArchiveV2,
+ AkeruMemoryCandidate,
+ AkeruMemoryRevision,
+ EnvironmentId,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ candidateDecisionInput,
+ factDeleteInput,
+ factEditInput,
+ importApplyInput,
+ importStateForThread,
+ memoryErrorMessage,
+} from "./BotMemorySheet";
+import { resolveBotThreadTarget } from "./botThreadRuntime.logic";
+
+const threadRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));
+const decodeArchive = Schema.decodeUnknownSync(AkeruMemoryArchiveV2);
+const revision = Schema.decodeUnknownSync(AkeruMemoryRevision)({
+ id: "memory-3",
+ rootId: "root-1",
+ revision: 3,
+ partition: { tenantId: "tenant-1", scope: "bot", partitionId: "bot-1" },
+ entityKind: "bot",
+ entityId: "bot-1",
+ kind: "fact",
+ value: {},
+ fact: "The user prefers short answers.",
+ sourceThreadId: "thread-1",
+ sourceMessageId: null,
+ authorBotId: "bot-1",
+ initiatingUserId: "user-1",
+ createdAt: "2026-08-31T00:00:00.000Z",
+ confirmedAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+ confidence: 0.9,
+ approvalState: "approved",
+ supersedesId: "memory-2",
+ supersededById: null,
+ visibility: "private",
+ deletionState: "active",
+ pinned: false,
+ sensitive: false,
+ affectedBotIds: ["bot-1"],
+});
+const candidate = Schema.decodeUnknownSync(AkeruMemoryCandidate)({
+ candidateId: "candidate-1",
+ tenantId: "tenant-1",
+ initiatingUserId: "user-1",
+ sourceThreadId: "thread-1",
+ sourceMessageId: null,
+ authorBotId: "bot-1",
+ fact: "The user works in New York.",
+ scope: "private",
+ sensitive: false,
+ confidence: 0.8,
+ affectedBotIds: ["bot-1"],
+ pendingUpdate: null,
+ status: "pending",
+ createdAt: "2026-08-31T00:00:00.000Z",
+ decidedAt: null,
+ decidedMemoryRootId: null,
+});
+
+describe("BotMemorySheet", () => {
+ it("renders facts, revision history, pending decisions, transfer controls, and failures", () => {
+ const source = NodeFS.readFileSync(new URL("./BotMemorySheet.tsx", import.meta.url), "utf8");
+ expect(source).toContain('data-testid="memory-fact"');
+ expect(source).toContain("revisions");
+ expect(source).toContain('data-testid="pending-memory"');
+ expect(source).toContain('data-testid="memory-import-preview"');
+ expect(source).toContain('role="alert"');
+ expect(source).toContain("Preview import");
+ expect(source).toContain("Apply import");
+ });
+
+ it("uses the displayed revision for edits and exposes a stale-conflict retry boundary", () => {
+ const input = factEditInput(threadRef, revision, " Updated fact ");
+ expect(input.input).toMatchObject({
+ threadId: "thread-1",
+ mutation: {
+ operation: "fact.edit",
+ memoryId: "root-1",
+ expectedRevision: 3,
+ fact: "Updated fact",
+ },
+ });
+ expect(
+ factEditInput(threadRef, { ...revision, revision: 4 }, "Updated fact").input.mutation
+ .expectedRevision,
+ ).toBe(4);
+ });
+
+ it("sends optimistic concurrency data when deleting", () => {
+ expect(factDeleteInput(threadRef, revision).input.mutation).toEqual({
+ operation: "fact.delete",
+ memoryId: "root-1",
+ expectedRevision: 3,
+ });
+ });
+
+ it("builds explicit approve and reject decisions", () => {
+ expect(
+ candidateDecisionInput(threadRef, candidate, "approve", "Approved fact", "bot").input.mutation
+ .decision,
+ ).toEqual({
+ candidateId: "candidate-1",
+ decision: "approve",
+ fact: "Approved fact",
+ scope: "bot",
+ });
+ expect(candidateDecisionInput(threadRef, candidate, "reject").input.mutation.decision).toEqual({
+ candidateId: "candidate-1",
+ decision: "reject",
+ });
+ });
+
+ it("applies the exact thread preview", () => {
+ const archive = decodeArchive({
+ schemaVersion: 2,
+ anchorThreadId: "thread-1",
+ target: "thread",
+ complete: true,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ files: [],
+ revisions: [],
+ conversations: [],
+ manifestSha256: "a".repeat(64),
+ });
+ const state = {
+ threadRef,
+ archive,
+ preview: { previewHash: "b".repeat(64), items: [] },
+ };
+ const input = importApplyInput(state);
+ expect(input.input).toMatchObject({
+ threadId: "thread-1",
+ target: "thread",
+ previewHash: "b".repeat(64),
+ });
+ expect(
+ importStateForThread(
+ state,
+ scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-2")),
+ ),
+ ).toBeNull();
+ });
+
+ it("keeps server failures and falls back for unknown errors", () => {
+ expect(memoryErrorMessage(new Error("Revision conflict."))).toBe("Revision conflict.");
+ expect(memoryErrorMessage(null)).toBe("Memory request failed.");
+ });
+
+ it("wires the authorized bot thread into the panel", () => {
+ const route = NodeFS.readFileSync(
+ new URL("../../routes/_chat.bots.$botId.tsx", import.meta.url),
+ "utf8",
+ );
+ expect(route).toContain("useBotThreadRef(botId)");
+ expect(route).toContain("threadRef={threadRef}");
+ });
+
+ it("keeps memory and chat bound to the latest active bot conversation", () => {
+ expect(
+ resolveBotThreadTarget(
+ "bot-1",
+ "env-1",
+ [
+ {
+ environmentId: "env-1",
+ id: "thread-selected",
+ botId: "bot-1",
+ updatedAt: "2026-08-30T00:00:00.000Z",
+ archivedAt: null,
+ deletedAt: null,
+ },
+ {
+ environmentId: "env-1",
+ id: "thread-newer",
+ botId: "bot-1",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+ archivedAt: null,
+ deletedAt: null,
+ },
+ ],
+ "/env-1/thread-selected",
+ ),
+ ).toMatchObject({ threadId: "thread-newer" });
+
+ const runtime = NodeFS.readFileSync(
+ new URL("./useBotThreadRuntime.ts", import.meta.url),
+ "utf8",
+ );
+ expect(runtime).toContain("resolveBotThreadTarget(");
+ });
+});
diff --git a/apps/web/src/components/roster/BotMemorySheet.tsx b/apps/web/src/components/roster/BotMemorySheet.tsx
new file mode 100644
index 000000000..17bea1f36
--- /dev/null
+++ b/apps/web/src/components/roster/BotMemorySheet.tsx
@@ -0,0 +1,507 @@
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ AkeruMemoryArchiveV2,
+ type AkeruMemoryCandidate,
+ type AkeruMemoryImportPreview,
+ type AkeruMemoryRevision,
+ type AkeruMemoryTargetScope,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import { useState } from "react";
+
+import { memoryEnvironment } from "../../state/memory";
+import { useEnvironmentQuery } from "../../state/query";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { Sheet, SheetHeader, SheetPanel, SheetPopup, SheetTitle } from "../ui/sheet";
+import { Textarea } from "../ui/textarea";
+
+const SCOPES: readonly AkeruMemoryTargetScope[] = [
+ "private",
+ "bot",
+ "project",
+ "group",
+ "workspace",
+];
+const decodeMemoryArchive = Schema.decodeUnknownEffect(AkeruMemoryArchiveV2);
+
+type ImportState = {
+ readonly threadRef: ScopedThreadRef;
+ readonly archive: AkeruMemoryArchiveV2;
+ readonly preview: AkeruMemoryImportPreview;
+};
+
+export function factEditInput(
+ threadRef: ScopedThreadRef,
+ memory: AkeruMemoryRevision,
+ fact: string,
+) {
+ return {
+ environmentId: threadRef.environmentId,
+ input: {
+ threadId: threadRef.threadId,
+ mutation: {
+ operation: "fact.edit" as const,
+ memoryId: memory.rootId,
+ expectedRevision: memory.revision,
+ fact: fact.trim(),
+ },
+ },
+ };
+}
+
+export function factDeleteInput(threadRef: ScopedThreadRef, memory: AkeruMemoryRevision) {
+ return {
+ environmentId: threadRef.environmentId,
+ input: {
+ threadId: threadRef.threadId,
+ mutation: {
+ operation: "fact.delete" as const,
+ memoryId: memory.rootId,
+ expectedRevision: memory.revision,
+ },
+ },
+ };
+}
+
+export function candidateDecisionInput(
+ threadRef: ScopedThreadRef,
+ candidate: AkeruMemoryCandidate,
+ decision: "approve" | "reject",
+ fact = candidate.fact,
+ scope = candidate.scope,
+) {
+ return {
+ environmentId: threadRef.environmentId,
+ input: {
+ threadId: threadRef.threadId,
+ mutation: {
+ operation: "candidate.decide" as const,
+ decision:
+ decision === "approve"
+ ? { candidateId: candidate.candidateId, decision, fact: fact.trim(), scope }
+ : { candidateId: candidate.candidateId, decision },
+ },
+ },
+ };
+}
+
+export function importStateForThread(state: ImportState | null, threadRef: ScopedThreadRef) {
+ return state?.threadRef.environmentId === threadRef.environmentId &&
+ state.threadRef.threadId === threadRef.threadId
+ ? state
+ : null;
+}
+
+export function importApplyInput(state: ImportState) {
+ return {
+ environmentId: state.threadRef.environmentId,
+ input: {
+ threadId: state.threadRef.threadId,
+ target: "thread" as const,
+ archive: state.archive,
+ previewHash: state.preview.previewHash,
+ },
+ };
+}
+
+export function memoryErrorMessage(error: unknown) {
+ return error instanceof Error && error.message.trim() ? error.message : "Memory request failed.";
+}
+
+function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]) {
+ return memoryErrorMessage(squashAtomCommandFailure(result));
+}
+
+function downloadArchive(archive: AkeruMemoryArchiveV2) {
+ const url = URL.createObjectURL(
+ new Blob([JSON.stringify(archive, null, 2)], { type: "application/json" }),
+ );
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = `akeru-memory-${archive.anchorThreadId}.json`;
+ anchor.click();
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+}
+
+function MemoryFact({
+ memory,
+ history,
+ busy,
+ onEdit,
+ onDelete,
+}: {
+ readonly memory: AkeruMemoryRevision;
+ readonly history: readonly AkeruMemoryRevision[];
+ readonly busy: boolean;
+ readonly onEdit: (fact: string) => void;
+ readonly onDelete: () => void;
+}) {
+ const [editing, setEditing] = useState(false);
+ const [fact, setFact] = useState(memory.fact);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+
+ return (
+ <article className="rounded-lg border border-border p-3" data-testid="memory-fact">
+ {editing ? (
+ <div className="space-y-2">
+ <Textarea
+ aria-label="Memory fact"
+ value={fact}
+ rows={3}
+ onChange={(event) => setFact(event.currentTarget.value)}
+ />
+ <div className="flex justify-end gap-2">
+ <Button size="xs" variant="ghost" onClick={() => setEditing(false)}>
+ Cancel
+ </Button>
+ <Button size="xs" disabled={busy || !fact.trim()} onClick={() => onEdit(fact)}>
+ Save
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <>
+ <p className="whitespace-pre-wrap text-sm leading-5">{memory.fact}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-1.5">
+ <Badge variant="outline">{memory.partition.scope}</Badge>
+ <span className="text-xs text-muted-foreground">Revision {memory.revision}</span>
+ {memory.pinned ? <Badge variant="secondary">Pinned</Badge> : null}
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <Button size="xs" variant="outline" disabled={busy} onClick={() => setEditing(true)}>
+ Edit
+ </Button>
+ <Button
+ size="xs"
+ variant={confirmDelete ? "destructive" : "ghost"}
+ disabled={busy}
+ onClick={() => (confirmDelete ? onDelete() : setConfirmDelete(true))}
+ >
+ {confirmDelete ? "Delete memory" : "Delete"}
+ </Button>
+ </div>
+ </>
+ )}
+ {history.length > 1 ? (
+ <details className="mt-3 border-t border-border pt-2 text-xs">
+ <summary className="cursor-pointer text-muted-foreground">
+ {history.length} revisions
+ </summary>
+ <ol className="mt-2 space-y-2">
+ {history.toReversed().map((revision) => (
+ <li key={revision.id}>
+ <span className="font-medium">Revision {revision.revision}</span>
+ <p className="mt-0.5 whitespace-pre-wrap text-muted-foreground">{revision.fact}</p>
+ </li>
+ ))}
+ </ol>
+ </details>
+ ) : null}
+ </article>
+ );
+}
+
+function PendingMemory({
+ candidate,
+ busy,
+ onDecide,
+}: {
+ readonly candidate: AkeruMemoryCandidate;
+ readonly busy: boolean;
+ readonly onDecide: (
+ decision: "approve" | "reject",
+ fact: string,
+ scope: AkeruMemoryTargetScope,
+ ) => void;
+}) {
+ const [fact, setFact] = useState(candidate.fact);
+ const [scope, setScope] = useState(candidate.scope);
+ return (
+ <article
+ className="space-y-2 rounded-lg border border-warning/40 bg-warning/5 p-3"
+ data-testid="pending-memory"
+ >
+ <Textarea
+ aria-label="Pending memory fact"
+ value={fact}
+ rows={3}
+ onChange={(event) => setFact(event.currentTarget.value)}
+ />
+ <Select
+ value={scope}
+ onValueChange={(value) => value && setScope(value as AkeruMemoryTargetScope)}
+ >
+ <SelectTrigger aria-label="Pending memory scope">
+ <SelectValue>{scope}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ {SCOPES.map((value) => (
+ <SelectItem key={value} value={value}>
+ {value}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ <div className="flex justify-end gap-2">
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => onDecide("reject", fact, scope)}
+ >
+ Reject
+ </Button>
+ <Button
+ size="xs"
+ disabled={busy || !fact.trim()}
+ onClick={() => onDecide("approve", fact, scope)}
+ >
+ Approve
+ </Button>
+ </div>
+ </article>
+ );
+}
+
+export function BotMemorySheet({
+ open,
+ onOpenChange,
+ threadRef,
+}: {
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ readonly threadRef: ScopedThreadRef | null;
+}) {
+ const query = useEnvironmentQuery(
+ threadRef
+ ? memoryEnvironment.inspect({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId },
+ })
+ : null,
+ );
+ const mutate = useAtomCommand(memoryEnvironment.mutate, { reportFailure: false });
+ const exportArchive = useAtomCommand(memoryEnvironment.exportArchive, { reportFailure: false });
+ const previewImport = useAtomCommand(memoryEnvironment.previewImport, { reportFailure: false });
+ const applyImport = useAtomCommand(memoryEnvironment.applyImport, { reportFailure: false });
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [importState, setImportState] = useState<ImportState | null>(null);
+ const [clearPending, setClearPending] = useState(false);
+ const currentImportState = threadRef ? importStateForThread(importState, threadRef) : null;
+
+ const runMutation = async (input: Parameters<typeof mutate>[0]) => {
+ setBusy(true);
+ setError(null);
+ const result = await mutate(input);
+ setBusy(false);
+ if (result._tag === "Failure") setError(failureMessage(result));
+ return result._tag !== "Failure";
+ };
+
+ if (!threadRef) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetPopup className="max-w-2xl" side="right">
+ <SheetHeader>
+ <SheetTitle>Memory</SheetTitle>
+ </SheetHeader>
+ <SheetPanel>
+ <p className="text-sm text-muted-foreground">Start a conversation to manage memory.</p>
+ </SheetPanel>
+ </SheetPopup>
+ </Sheet>
+ );
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetPopup className="max-w-2xl" side="right">
+ <SheetHeader>
+ <SheetTitle>Memory</SheetTitle>
+ </SheetHeader>
+ <SheetPanel className="space-y-6">
+ {(error ?? query.error) ? (
+ <div
+ role="alert"
+ className="rounded-lg bg-destructive/8 p-3 text-sm text-destructive-foreground"
+ >
+ {error ?? query.error}
+ </div>
+ ) : null}
+ {query.isPending && !query.data ? (
+ <p className="text-sm text-muted-foreground">Loading memory...</p>
+ ) : null}
+ {query.data ? (
+ <>
+ <section className="space-y-3">
+ <h3 className="text-sm font-medium">Facts</h3>
+ {query.data.durable.length ? (
+ query.data.durable.map((memory) => (
+ <MemoryFact
+ key={memory.rootId}
+ memory={memory}
+ history={
+ query.data?.histories.find((item) => item.rootId === memory.rootId)
+ ?.revisions ?? [memory]
+ }
+ busy={busy}
+ onEdit={(fact) => void runMutation(factEditInput(threadRef, memory, fact))}
+ onDelete={() => void runMutation(factDeleteInput(threadRef, memory))}
+ />
+ ))
+ ) : (
+ <p className="text-sm text-muted-foreground">No saved facts.</p>
+ )}
+ </section>
+
+ {query.data.pending.length ? (
+ <section className="space-y-3">
+ <h3 className="text-sm font-medium">Pending</h3>
+ {query.data.pending.map((candidate) => (
+ <PendingMemory
+ key={candidate.candidateId}
+ candidate={candidate}
+ busy={busy}
+ onDecide={(decision, fact, scope) =>
+ void runMutation(
+ candidateDecisionInput(threadRef, candidate, decision, fact, scope),
+ )
+ }
+ />
+ ))}
+ </section>
+ ) : null}
+
+ <section className="space-y-3">
+ <h3 className="text-sm font-medium">Conversation</h3>
+ <p className="text-sm text-muted-foreground">
+ {query.data.conversation.current
+ ? `${query.data.conversation.current.generationCount} generations`
+ : "No conversation memory."}
+ </p>
+ <Button
+ size="sm"
+ variant={clearPending ? "destructive" : "outline"}
+ disabled={busy || !query.data.conversation.current}
+ onClick={() => {
+ if (!clearPending) return setClearPending(true);
+ void runMutation({
+ environmentId: threadRef.environmentId,
+ input: {
+ threadId: threadRef.threadId,
+ mutation: { operation: "conversation.clear" },
+ },
+ }).then((success) => success && setClearPending(false));
+ }}
+ >
+ {clearPending ? "Clear conversation memory" : "Clear"}
+ </Button>
+ </section>
+
+ <section className="space-y-3">
+ <h3 className="text-sm font-medium">Transfer</h3>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={busy}
+ onClick={() => {
+ setBusy(true);
+ setError(null);
+ void exportArchive({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId, complete: true, target: "thread" },
+ }).then((result) => {
+ setBusy(false);
+ if (result._tag === "Failure") setError(failureMessage(result));
+ else downloadArchive(result.value);
+ });
+ }}
+ >
+ Export thread
+ </Button>
+ <label className="inline-flex">
+ <Input
+ className="sr-only"
+ aria-label="Import memory archive"
+ type="file"
+ accept="application/json,.json"
+ disabled={busy}
+ onChange={(event) => {
+ const file = event.currentTarget.files?.[0];
+ if (!file) return;
+ setBusy(true);
+ setError(null);
+ setImportState(null);
+ void file
+ .text()
+ .then(JSON.parse)
+ .then((value) => Effect.runPromise(decodeMemoryArchive(value)))
+ .then((archive) =>
+ previewImport({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId, target: "thread", archive },
+ }).then((result) => {
+ setBusy(false);
+ if (result._tag === "Failure") setError(failureMessage(result));
+ else setImportState({ threadRef, archive, preview: result.value });
+ }),
+ )
+ .catch((cause: unknown) => {
+ setBusy(false);
+ setError(
+ cause instanceof Error ? cause.message : "Invalid memory archive.",
+ );
+ });
+ }}
+ />
+ <span className="inline-flex h-8 cursor-pointer items-center rounded-lg border border-input px-3 text-sm">
+ Preview import
+ </span>
+ </label>
+ </div>
+ {currentImportState ? (
+ <div
+ className="rounded-lg border border-border p-3"
+ data-testid="memory-import-preview"
+ >
+ <ul className="space-y-1 text-sm">
+ {currentImportState.preview.items.map((item) => (
+ <li key={item.rootId}>
+ <span className="font-medium">{item.classification}</span> {item.reason}
+ </li>
+ ))}
+ </ul>
+ <Button
+ className="mt-3"
+ size="sm"
+ disabled={busy}
+ onClick={() => {
+ setBusy(true);
+ setError(null);
+ void applyImport(importApplyInput(currentImportState)).then((result) => {
+ setBusy(false);
+ if (result._tag === "Failure") setError(failureMessage(result));
+ else setImportState(null);
+ });
+ }}
+ >
+ Apply import
+ </Button>
+ </div>
+ ) : null}
+ </section>
+ </>
+ ) : null}
+ </SheetPanel>
+ </SheetPopup>
+ </Sheet>
+ );
+}
diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.ts b/apps/web/src/components/roster/botThreadRuntime.logic.ts
index d4daad714..c0206fe25 100644
--- a/apps/web/src/components/roster/botThreadRuntime.logic.ts
+++ b/apps/web/src/components/roster/botThreadRuntime.logic.ts
@@ -11,6 +11,8 @@ import type {
OrchestrationThreadActivity,
} from "@t3tools/contracts";
+import { parseChatPath } from "./roster.logic";
+
const botTurnSubmissions = new Map<
string,
{
@@ -197,6 +199,20 @@ export function findLatestBotThreadTarget(
return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;
}
+export function resolveBotThreadTarget(
+ botId: string,
+ environmentId: string,
+ threads: Parameters<typeof findLatestBotThreadTarget>[2],
+ rememberedPath: string | undefined,
+) {
+ const latest = findLatestBotThreadTarget(botId, environmentId, threads);
+ if (latest) return latest;
+ const remembered = rememberedPath ? parseChatPath(rememberedPath) : null;
+ return remembered?.kind === "thread" && remembered.environmentId === environmentId
+ ? remembered
+ : null;
+}
+
export function findLatestGroupThreadTarget(
groupId: string,
environmentId: string,
diff --git a/apps/web/src/components/roster/useBotThreadRef.ts b/apps/web/src/components/roster/useBotThreadRef.ts
new file mode 100644
index 000000000..c85cafc10
--- /dev/null
+++ b/apps/web/src/components/roster/useBotThreadRef.ts
@@ -0,0 +1,28 @@
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import { useMemo } from "react";
+
+import { usePrimaryEnvironmentId } from "../../state/environments";
+import { useThreadShell, useThreadShells } from "../../state/entities";
+import { resolveBotThreadTarget } from "./botThreadRuntime.logic";
+import { useRosterStore } from "./rosterStore";
+
+export function useBotThreadRef(botId: string): ScopedThreadRef | null {
+ const environmentId = usePrimaryEnvironmentId();
+ const threads = useThreadShells();
+ const rememberedPath = useRosterStore((state) => state.chatPathByBotId[botId]);
+ const candidate = environmentId
+ ? resolveBotThreadTarget(botId, environmentId, threads, rememberedPath)
+ : null;
+ const ref = useMemo(
+ () =>
+ candidate
+ ? scopeThreadRef(
+ EnvironmentId.make(candidate.environmentId),
+ ThreadId.make(candidate.threadId),
+ )
+ : null,
+ [candidate?.environmentId, candidate?.threadId],
+ );
+ return useThreadShell(ref) ? ref : null;
+}
diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.ts
index 664e46c29..e930081b1 100644
--- a/apps/web/src/components/roster/useBotThreadRuntime.ts
+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts
@@ -32,12 +32,11 @@ import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import {
acceptBotTurnSubmission,
buildBotTurnStartInput,
- findLatestBotThreadTarget,
joinOrStartThreadCreate,
releaseBotTurnSubmissionAfterObservation,
+ resolveBotThreadTarget,
reserveBotTurnSubmissionAfterObservation,
} from "./botThreadRuntime.logic";
-import { parseChatPath } from "./roster.logic";
import { useRosterStore } from "./rosterStore";
const NO_ENVIRONMENT = "" as EnvironmentId;
@@ -82,7 +81,6 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
const providers = useAtomValue(primaryServerProvidersAtom);
const rememberedPath = useRosterStore((state) => state.chatPathByBotId[botId]);
const bot = useRosterStore((state) => state.bots.find((candidate) => candidate.id === botId));
- const target = rememberedPath ? parseChatPath(rememberedPath) : null;
const primaryThreadShells = useMemo(
() =>
primaryEnvironmentId
@@ -90,20 +88,14 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
: [],
[primaryEnvironmentId, threadShells],
);
- const serverTarget = primaryEnvironmentId
- ? findLatestBotThreadTarget(botId, primaryEnvironmentId, primaryThreadShells)
+ const target = primaryEnvironmentId
+ ? resolveBotThreadTarget(botId, primaryEnvironmentId, primaryThreadShells, rememberedPath)
: null;
const rememberedThreadRef = useMemo<ScopedThreadRef | null>(() => {
- const candidate =
- serverTarget ??
- (target?.kind === "thread" && target.environmentId === primaryEnvironmentId ? target : null);
- return candidate
- ? scopeThreadRef(
- EnvironmentId.make(candidate.environmentId),
- ThreadId.make(candidate.threadId),
- )
+ return target
+ ? scopeThreadRef(EnvironmentId.make(target.environmentId), ThreadId.make(target.threadId))
: null;
- }, [primaryEnvironmentId, serverTarget, target]);
+ }, [target]);
const rememberedThread = useThreadShell(rememberedThreadRef);
const linkedThreadRef = rememberedThread ? rememberedThreadRef : null;
const retainedThreadRef = useRef<{ botId: string; threadRef: ScopedThreadRef | null }>({
diff --git a/apps/web/src/routes/_chat.bots.$botId.tsx b/apps/web/src/routes/_chat.bots.$botId.tsx
index 88870c749..ded9b1bf1 100644
--- a/apps/web/src/routes/_chat.bots.$botId.tsx
+++ b/apps/web/src/routes/_chat.bots.$botId.tsx
@@ -4,6 +4,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { BotThreadLanding } from "../components/roster/BotThreadLanding";
import { BotDetailsPanel } from "../components/roster/BotDetailsPanel";
import { useRosterStore } from "../components/roster/rosterStore";
+import { useBotThreadRef } from "../components/roster/useBotThreadRef";
import { toastManager } from "../components/ui/toast";
import { botEnvironment } from "../state/bots";
import { usePrimaryEnvironmentId } from "../state/environments";
@@ -13,6 +14,7 @@ function BotThreadRouteView() {
const { botId } = Route.useParams();
const environmentId = usePrimaryEnvironmentId();
const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
+ const threadRef = useBotThreadRef(botId);
const bot = useRosterStore((state) =>
state.bots.find((candidate) => candidate.id === botId && candidate.archivedAt === null),
);
@@ -24,6 +26,7 @@ function BotThreadRouteView() {
<BotDetailsPanel
key={bot.id}
bot={bot}
+ threadRef={threadRef}
onSaveBot={async ({
name,
label,
diff --git a/apps/web/src/state/memory.ts b/apps/web/src/state/memory.ts
new file mode 100644
index 000000000..5cbb16744
--- /dev/null
+++ b/apps/web/src/state/memory.ts
@@ -0,0 +1,5 @@
+import { createMemoryEnvironmentAtoms } from "@t3tools/client-runtime/state/memory";
+
+import { connectionAtomRuntime } from "../connection/runtime";
+
+export const memoryEnvironment = createMemoryEnvironmentAtoms(connectionAtomRuntime);