-
Notifications
You must be signed in to change notification settings - Fork 106
feat(memory): suggest memories from completed chats #67
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+706
−64
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" || | ||
| (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, | ||
| ); | ||
| } | ||
| }, | ||
| ); | ||
| }, []); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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([]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?