Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app/AppShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ import { DEFAULT_CHAT_TITLE } from "@/features/chat/lib/sessionTitle";
import { useAppStartup } from "./hooks/useAppStartup";
import { useRemoteSessionExperimentReconciliation } from "@/features/chat/hooks/useRemoteSessionExperimentReconciliation";
import { useCompletionNotifications } from "@/shared/hooks/useCompletionNotifications";
import { useMemoryNoticer } from "@/features/me/hooks/useMemoryNoticer";
import { MemoryProposalToasts } from "@/features/me/ui/MemoryProposalToasts";
import { useHomeSessionStateSync } from "./hooks/useHomeSessionStateSync";
import { useHomeWidgetStore } from "@/features/home/stores/homeWidgetStore";
Expand Down Expand Up @@ -1039,6 +1040,7 @@ export function AppShell({
);

useCompletionNotifications(handleNavigateToSession);
useMemoryNoticer();

useEffect(() => {
let didCancel = false;
Expand Down
36 changes: 36 additions & 0 deletions src/features/me/hooks/__tests__/useMemoryNoticer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import { noticerTargetForCompletedTurn } from "../useMemoryNoticer";

describe("noticerTargetForCompletedTurn", () => {
it("uses the completed Goose session's exact provider and model", () => {
expect(
noticerTargetForCompletedTurn("streaming", "idle", {
harnessId: "goose",
modelProviderId: "anthropic",
modelId: "claude-sonnet",
modelName: "Claude Sonnet",
}),
).toEqual({ providerId: "anthropic", modelId: "claude-sonnet" });
});

it("skips external harnesses instead of falling back", () => {
expect(
noticerTargetForCompletedTurn("streaming", "idle", {
harnessId: "claude-acp",
}),
).toBeNull();
});

it("only schedules when an active turn becomes idle", () => {
const target = {
harnessId: "goose",
modelProviderId: "openai",
modelId: "gpt",
modelName: "GPT",
} as const;
expect(noticerTargetForCompletedTurn("idle", "idle", target)).toBeNull();
expect(
noticerTargetForCompletedTurn("thinking", "idle", target),
).not.toBeNull();
});
});
60 changes: 60 additions & 0 deletions src/features/me/hooks/useMemoryNoticer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useEffect } from "react";

import { useChatSessionStore } from "@/features/chat/stores/chatSessionStore";
import { useChatStore } from "@/features/chat/stores/chatStore";
import type { SessionExecutionTarget } from "@/features/chat/lib/sessionExecutionTarget";
import { scheduleNoticerPass } from "../lib/noticerTrigger";

export function noticerTargetForCompletedTurn(
before: string | undefined,
now: string | undefined,
target: SessionExecutionTarget | undefined,
): { providerId: string; modelId: string } | null {
if (
now !== "idle" ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't these be Enums?

(before !== "streaming" && before !== "thinking") ||
target?.harnessId !== "goose" ||
!target.modelProviderId ||
!target.modelId
)
return null;
return { providerId: target.modelProviderId, modelId: target.modelId };
}

/**
* Schedule memory extraction when a foreground assistant turn finishes.
*
* Completion is store state, not send-path control flow: queued sends,
* cancellation and lifecycle transitions all converge here. This mirrors the
* existing completion-notification owner instead of coupling memory to
* `dispatchPrompt` internals.
*/
export function useMemoryNoticer(): void {
useEffect(() => {
return useChatStore.subscribe(
(state) => state.sessionStateById,
(current, previous) => {
const ids = new Set([
...Object.keys(current),
...Object.keys(previous),
]);
for (const sessionId of ids) {
const now = current[sessionId]?.chatState;
const before = previous[sessionId]?.chatState;
const target = noticerTargetForCompletedTurn(
before,
now,
useChatSessionStore.getState().getSession(sessionId)
?.executionTarget,
);
if (!target) continue;
scheduleNoticerPass(
sessionId,
() => useChatStore.getState().messagesBySession[sessionId] ?? [],
target,
);
}
},
);
}, []);
}
97 changes: 97 additions & 0 deletions src/features/me/lib/__tests__/memoryNoticer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import {
buildNoticerSystemPrompt,
NOTICER_VOCABULARY,
parseNoticerOutput,
} from "../memoryNoticer";

describe("buildNoticerSystemPrompt", () => {
it("carries the bounded vocabulary and the caps", () => {
const prompt = buildNoticerSystemPrompt([]);
for (const name of NOTICER_VOCABULARY) {
expect(prompt).toContain(name);
}
expect(prompt).toContain("Never invent a narrower topic name");
expect(prompt).toContain("untrusted input");
});

it("prefers the user's existing topics when they have some", () => {
const prompt = buildNoticerSystemPrompt(["Woodworking", "Family"]);
expect(prompt).toContain("Woodworking, Family");
expect(prompt).toContain("always prefer routing to one of these");
});
});

describe("parseNoticerOutput", () => {
it("parses candidates and keeps vocabulary topics", () => {
const out = parseNoticerOutput(
'[{"content": "Youngest has soccer Monday and Thursday evenings.", "topic": "Home"}]',
[],
);
expect(out).toEqual([
{
content: "Youngest has soccer Monday and Thursday evenings.",
topic: "Home",
},
]);
});

it("accepts the user's existing topics as routes", () => {
const out = parseNoticerOutput(
'[{"content": "Uses walnut for most builds.", "topic": "Woodworking"}]',
["Woodworking"],
);
expect(out).toHaveLength(1);
expect(out[0].topic).toBe("Woodworking");
});

it("drops candidates with out-of-vocabulary topic names", () => {
const out = parseNoticerOutput(
'[{"content": "Kid plays striker.", "topic": "Soccer"}]',
[],
);
expect(out).toEqual([]);
});

it("routes null topics to the spine", () => {
const out = parseNoticerOutput(
'[{"content": "Always ask before deleting anything.", "topic": null}]',
[],
);
expect(out[0].topic).toBeNull();
});

it("tolerates code fences and surrounding prose", () => {
const out = parseNoticerOutput(
'Here you go:\n```json\n[{"content": "Vegetarian.", "topic": "Home"}]\n```',
[],
);
expect(out).toHaveLength(1);
});

it("treats NONE, junk, and empty as no candidates", () => {
expect(parseNoticerOutput("NONE", [])).toEqual([]);
expect(parseNoticerOutput("none of note", [])).toEqual([]);
expect(parseNoticerOutput("not json at all", [])).toEqual([]);
expect(parseNoticerOutput(null, [])).toEqual([]);
expect(parseNoticerOutput('{"content": "not an array"}', [])).toEqual([]);
});

it("caps the number of candidates per pass", () => {
const many = JSON.stringify(
Array.from({ length: 8 }, (_, i) => ({
content: `Fact number ${i}.`,
topic: "Home",
})),
);
expect(parseNoticerOutput(many, []).length).toBeLessThanOrEqual(3);
});

it("drops oversized and empty content", () => {
const out = parseNoticerOutput(
`[{"content": "", "topic": "Home"}, {"content": "${"x".repeat(400)}", "topic": "Home"}]`,
[],
);
expect(out).toEqual([]);
});
});
128 changes: 128 additions & 0 deletions src/features/me/lib/__tests__/noticerTrigger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Message } from "@/shared/types/messages";

const mocks = vi.hoisted(() => ({
noticeFromTranscript: vi.fn(async (_transcript: string) => 0),
}));

vi.mock("../memoryNoticer", () => ({
noticeFromTranscript: mocks.noticeFromTranscript,
}));

import {
resetNoticerTracking,
scheduleNoticerPass,
userTranscript,
} from "../noticerTrigger";

function userMessage(text: string): Message {
return {
id: `m-${Math.random().toString(36).slice(2)}`,
role: "user",
created: Date.now(),
content: [{ type: "text", text }],
};
}

function assistantMessage(text: string): Message {
return {
id: `m-${Math.random().toString(36).slice(2)}`,
role: "assistant",
created: Date.now(),
content: [{ type: "text", text }],
};
}

afterEach(() => {
resetNoticerTracking();
mocks.noticeFromTranscript.mockClear();
vi.useRealTimers();
});

describe("userTranscript", () => {
it("keeps only the user's own words", () => {
const transcript = userTranscript([
userMessage("My kid has soccer Mondays."),
assistantMessage("Great, here's a schedule."),
userMessage("And the dog goes out Wednesdays."),
]);
expect(transcript).toContain("soccer Mondays");
expect(transcript).toContain("dog goes out Wednesdays");
expect(transcript).not.toContain("here's a schedule");
});
});

describe("scheduleNoticerPass", () => {
it("debounces: rescheduling resets the timer, one pass per lull", async () => {
vi.useFakeTimers();
const messages = [userMessage("First.")];
scheduleNoticerPass(
"s1",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 1000 },
);
vi.advanceTimersByTime(600);
messages.push(userMessage("Second."));
scheduleNoticerPass(
"s1",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 1000 },
);
vi.advanceTimersByTime(600);
expect(mocks.noticeFromTranscript).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(500);
expect(mocks.noticeFromTranscript).toHaveBeenCalledTimes(1);
expect(mocks.noticeFromTranscript.mock.calls[0][0]).toContain("Second.");
});

it("triggers on new user text but extracts the whole conversation", async () => {
vi.useFakeTimers();
const messages = [userMessage("Old fact.")];
scheduleNoticerPass(
"s2",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 10 },
);
await vi.advanceTimersByTimeAsync(20);
expect(mocks.noticeFromTranscript).toHaveBeenCalledTimes(1);

messages.push(assistantMessage("ok"), userMessage("New fact."));
scheduleNoticerPass(
"s2",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 10 },
);
await vi.advanceTimersByTimeAsync(20);
expect(mocks.noticeFromTranscript).toHaveBeenCalledTimes(2);
// Single messages in isolation read as nothing worth keeping, so the
// pass sees the full conversation; the queue and tombstones dedupe.
const second = mocks.noticeFromTranscript.mock.calls[1][0];
expect(second).toContain("New fact.");
expect(second).toContain("Old fact.");
});

it("skips the pass entirely when there is no new user text", async () => {
vi.useFakeTimers();
const messages = [userMessage("Only fact.")];
scheduleNoticerPass(
"s3",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 10 },
);
await vi.advanceTimersByTimeAsync(20);
messages.push(assistantMessage("assistant only"));
scheduleNoticerPass(
"s3",
() => messages,
{ providerId: "p", modelId: "m" },
{ delayMs: 10 },
);
await vi.advanceTimersByTimeAsync(20);
expect(mocks.noticeFromTranscript).toHaveBeenCalledTimes(1);
});
});
Loading
Loading