Skip to content
Draft
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
8 changes: 8 additions & 0 deletions backend/internal/domain/session_search.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,9 @@ type SessionSearchHit struct {
// MatchTotalCapped reports that the ranking stage hit its candidate cap,
// so MatchTotal is a floor and the exact total needs a count.
MatchTotalCapped bool
// NamedForQuery reports that the session's name holds every typed word:
// the ranking's name tier, which put the session ahead of any bm25 score.
NamedForQuery bool
}

// SessionSearchHighlight is one matched span in a snippet, in UTF-16 code units:
Expand Down Expand Up @@ -424,6 +427,11 @@ type SessionSearchResult struct {
// ReviewID is set when the match is in one of the session's reviewer chats,
// which is where opening the result goes.
ReviewID string `json:"reviewId,omitempty"`
// NamedForQuery reports that the session's name holds every typed word,
// which is why it ranks first. A desktop merging several machines' lists
// keeps such sessions first: unlike bm25 scores, which depend on each
// machine's own index, a name match means the same thing on every machine.
NamedForQuery bool `json:"namedForQuery,omitempty"`
}

// SessionSearchCoverage says what the index can and cannot see.
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/httpd/apispec/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23826,6 +23826,8 @@ components:
type: string
messageId:
type: string
namedForQuery:
type: boolean
projectId:
type: string
projectName:
Expand Down
4 changes: 4 additions & 0 deletions backend/internal/httpd/controllers/session_search.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ type SessionSearchResult struct {
// ReviewID is set when the match is in one of the session's reviewer chats;
// opening the result opens that reviewer chat at the message.
ReviewID string `json:"reviewId,omitempty"`
// NamedForQuery is set when the session's name holds every typed word.
// Such sessions rank first, and a merge across machines keeps them first.
NamedForQuery bool `json:"namedForQuery,omitempty"`
}

// SessionSearchHighlight is one matched span inside a result's snippet.
Expand Down Expand Up @@ -304,6 +307,7 @@ func sessionSearchResults(results []domain.SessionSearchResult) []SessionSearchR
ResumeCommand: item.ResumeCommand,
SessionMatches: item.SessionMatches,
ReviewID: item.ReviewID,
NamedForQuery: item.NamedForQuery,
})
}
return out
Expand Down
8 changes: 5 additions & 3 deletions backend/internal/httpd/controllers/session_search_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ func TestSearchSessionsGroupsBySessionByDefault(t *testing.T) {
Group: domain.SessionSearchGroupSession,
Results: []domain.SessionSearchResult{{
SessionID: "proj-1", Kind: domain.SessionSearchKindUser, Snippet: "flaky", SessionMatches: 4,
ReviewID: "review-1",
ReviewID: "review-1", NamedForQuery: true,
}},
}}
srv := newSessionSearchServer(t, svc)
Expand All @@ -335,14 +335,16 @@ func TestSearchSessionsGroupsBySessionByDefault(t *testing.T) {
Results []struct {
SessionMatches int `json:"sessionMatches"`
ReviewID string `json:"reviewId"`
NamedForQuery bool `json:"namedForQuery"`
} `json:"results"`
}
if err := json.Unmarshal(body, &decoded); err != nil {
t.Fatalf("decode: %v", err)
}
// reviewId routes a reviewer-chat match to that reviewer chat.
// reviewId routes a reviewer-chat match to that reviewer chat;
// namedForQuery lets a merge across machines keep a name match first.
if decoded.Group != "session" || len(decoded.Results) != 1 || decoded.Results[0].SessionMatches != 4 ||
decoded.Results[0].ReviewID != "review-1" {
decoded.Results[0].ReviewID != "review-1" || !decoded.Results[0].NamedForQuery {
t.Fatalf("response = %s", body)
}

Expand Down
9 changes: 8 additions & 1 deletion backend/internal/service/sessionsearch/regressions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,10 +333,17 @@ func TestASessionNamedForTheQueryLeadsEvenWithNothingButItsName(t *testing.T) {
}

for _, query := range []string{"amp smoke test", "Amp ChatGPT AO smoke test"} {
got := sessionIDs(search(t, f.svc, query).Results)
results := search(t, f.svc, query).Results
got := sessionIDs(results)
if len(got) == 0 || got[0] != string(named.ID) {
t.Fatalf("%q = %v, want the session named for the query first", query, got)
}
// The result says so, so a merge across machines can keep it first.
for _, result := range results {
if want := result.SessionID == string(named.ID); result.NamedForQuery != want {
t.Fatalf("%q: %s namedForQuery = %v, want %v", query, result.SessionID, result.NamedForQuery, want)
}
}
}
}

Expand Down
1 change: 1 addition & 0 deletions backend/internal/service/sessionsearch/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,7 @@ func (s *Service) toResults(ctx context.Context, hits []domain.SessionSearchHit)
CreatedAt: hit.CreatedAt,
SessionMatches: hit.SessionMatches,
ReviewID: hit.ReviewID,
NamedForQuery: hit.NamedForQuery,
})
sessionIDs = append(sessionIDs, hit.SessionID)
projectIDs = append(projectIDs, hit.ProjectID)
Expand Down
4 changes: 2 additions & 2 deletions backend/internal/storage/sqlite/store/session_search_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ SELECT p.id, d.session_id, d.project_id, d.harness, d.kind,
COALESCE(t.title, ''), d.created_at, p.score, p.session_matches,
CASE WHEN ? = 1 THEN NULL ELSE t.body END,
p.match_total, p.candidate_count,
COALESCE(rv.id, '')
COALESCE(rv.id, ''), p.name_tier = 0
FROM page p
JOIN session_search_docs d ON d.id = p.id
LEFT JOIN session_search_text t ON t.id = p.id
Expand Down Expand Up @@ -458,7 +458,7 @@ func (s *Store) searchSessionSearchDocs(ctx context.Context, params domain.Sessi
if err := rows.Scan(
&docID, &hit.SessionID, &hit.ProjectID, &hit.Harness, &kind, &hit.MessageID, &hit.Seq,
&hit.Title, &createdAt, &hit.Rank, &hit.SessionMatches, &body, &hit.MatchTotal, &candidates,
&hit.ReviewID,
&hit.ReviewID, &hit.NamedForQuery,
); err != nil {
return nil, false, fmt.Errorf("scan session search hit: %w", err)
}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8375,6 +8375,7 @@ export interface components {
/** @enum {string} */
kind: "title" | "user" | "assistant" | "tool" | "command" | "path";
messageId?: string;
namedForQuery?: boolean;
projectId: string;
projectName?: string;
/** Format: double */
Expand Down
94 changes: 94 additions & 0 deletions frontend/src/renderer/components/CommandPalette.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { STANDALONE_WORKSPACE_ID, type WorkspaceSummary } from "../types/workspa
import { useUiStore } from "../stores/ui-store";
import { useSessionImportStore } from "../stores/session-import-store";
import { peekSessionSearchReveal, resetSessionSearchReveals } from "../lib/session-search-reveal";
import { sessionUiKey } from "../lib/hosts";

const navigateMock = vi.hoisted(() => vi.fn());
const spawnMock = vi.hoisted(() => vi.fn());
Expand Down Expand Up @@ -163,6 +164,10 @@ vi.mock("../lib/api-client", () => ({
GET: getMock,
POST: postMock,
},
apiErrorCode: (error: unknown) =>
typeof error === "object" && error !== null && typeof (error as { code?: unknown }).code === "string"
? (error as { code: string }).code
: undefined,
apiErrorMessage: (error: unknown, fallback = "Request failed") => {
if (error instanceof Error) return error.message;
if (typeof error === "object" && error !== null && "message" in error) {
Expand All @@ -172,6 +177,14 @@ vi.mock("../lib/api-client", () => ({
},
}));

// Search across machines is its own hook with its own tests; here it says what
// the other machines answered. By default there are none.
const remoteSearchMock = vi.hoisted(() => {
const none = { answers: [] as unknown[], settled: true };
return { none, value: none };
});
vi.mock("../hooks/useRemoteMachineSearch", () => ({ useRemoteMachineSearch: () => remoteSearchMock.value }));

vi.mock("../lib/host-clients", () => ({
clientForSessionHost: () => ({ GET: getMock, POST: postMock }),
clientForHost: () => ({ GET: getMock, POST: postMock }),
Expand Down Expand Up @@ -1488,6 +1501,7 @@ describe("CommandPalette New task", () => {
describe("CommandPalette session-text search", () => {
beforeEach(() => {
resetSessionSearchReveals();
remoteSearchMock.value = remoteSearchMock.none;
});

function searchResponse(results: unknown[], coverage: Record<string, unknown> = { state: "ready" }) {
Expand Down Expand Up @@ -1634,6 +1648,86 @@ describe("CommandPalette session-text search", () => {
expect(peekSessionSearchReveal("standalone-3")).toMatchObject({ messageId: "msg-1" });
});

it("searches every connected machine and opens a remote session on its machine", async () => {
mockSearch([hit]);
remoteSearchMock.value = { settled: true, answers: [
{ hostId: "h_azure", label: "AzureLinux", outcome: "searched", total: 1, results: [{ ...hit, messageId: "remote-msg", sessionName: "fix flake on azure" }] },
{ hostId: "h_old", label: "Old desk", outcome: "needs_update", total: 0, results: [] },
] };
renderPalette();
act(() => useUiStore.getState().setCommandPaletteOpen(true));
fireEvent.change(await screen.findByPlaceholderText(/search sessions/i), { target: { value: "flaky" } });

// The same session id on two machines is two sessions: both rows stay,
// and the remote one says where it is.
const remoteRow = await screen.findByText("fix flake on azure", {}, { timeout: 2_000 });
expect(screen.getByText("fix flake")).toBeInTheDocument();
expect(screen.getByText("AzureLinux · you · app · codex")).toBeInTheDocument();
expect(screen.getByTestId("palette-machines-not-searched").textContent).toBe("Not searched on Old desk (update AO there to search it).");

fireEvent.click(remoteRow);
expect(navigateMock).toHaveBeenCalledWith({
to: "/host/$hostId/project/$projectId/session/$sessionId",
params: { hostId: "h_azure", projectId: "proj-1", sessionId: "w-fix" },
});
// The match is handed to that machine's session, keyed by host and id.
expect(peekSessionSearchReveal(sessionUiKey("w-fix", "h_azure"))).toMatchObject({ messageId: "remote-msg" });
expect(peekSessionSearchReveal("w-fix")).toBeUndefined();
});

it("keeps this machine's answer until every machine has answered", async () => {
mockSearch([hit]);
remoteSearchMock.value = { settled: false, answers: [
{ hostId: "h_azure", label: "AzureLinux", outcome: "searched", total: 1, results: [{ ...hit, sessionName: "fix flake on azure" }] },
] };
renderPalette();
act(() => useUiStore.getState().setCommandPaletteOpen(true));
fireEvent.change(await screen.findByPlaceholderText(/search sessions/i), { target: { value: "flaky" } });

expect(await screen.findByText("fix flake", {}, { timeout: 2_000 })).toBeInTheDocument();
expect(screen.queryByText("fix flake on azure")).not.toBeInTheDocument();
expect(screen.queryByTestId("palette-machines-not-searched")).not.toBeInTheDocument();
});

// This machine's index can be off (AO_SESSION_SEARCH=off) or unopenable while
// its daemon runs on. That is one machine not answering: the machines that
// did answer still show, and the local failure is still said.
it("shows other machines' matches when this machine's search is unavailable", async () => {
getMock.mockImplementation(async (path: string) => {
if (path.includes("/search/index-status")) return { data: { coverage: { state: "unavailable" } } };
if (path.includes("/search/sessions")) {
return { error: { code: "SESSION_SEARCH_UNAVAILABLE", message: "Session search is not available on this daemon" } };
}
if (path === "/api/v1/conversations/search") return { data: { results: [] } };
return { data: {} };
});
remoteSearchMock.value = { settled: true, answers: [
{ hostId: "h_azure", label: "AzureLinux", outcome: "searched", total: 1, results: [{ ...hit, sessionName: "fix flake on azure" }] },
] };
renderPalette();
act(() => useUiStore.getState().setCommandPaletteOpen(true));
fireEvent.change(await screen.findByPlaceholderText(/search sessions/i), { target: { value: "flaky" } });

expect(await screen.findByText("fix flake on azure", {}, { timeout: 2_000 })).toBeInTheDocument();
expect(screen.getByText(/Session search is not available on this daemon/)).toBeInTheDocument();
});

it("opens a remote standalone session's match on that machine's standalone route", async () => {
mockSearch([]);
remoteSearchMock.value = { settled: true, answers: [
{ hostId: "h_azure", label: "AzureLinux", outcome: "searched", total: 1, results: [{ ...hit, sessionId: "standalone-9", projectId: "", sessionName: "kettle on azure" }] },
] };
renderPalette();
act(() => useUiStore.getState().setCommandPaletteOpen(true));
fireEvent.change(await screen.findByPlaceholderText(/search sessions/i), { target: { value: "flaky" } });

fireEvent.click(await screen.findByText("kettle on azure", {}, { timeout: 2_000 }));
expect(navigateMock).toHaveBeenCalledWith({
to: "/host/$hostId/session/$sessionId",
params: { hostId: "h_azure", sessionId: "standalone-9" },
});
});

it("opens a tool-output match without inventing a message anchor", async () => {
mockSearch([{ ...hit, kind: "command", messageId: undefined, snippet: "TS2304: cannot find name" }]);
renderPalette();
Expand Down
70 changes: 58 additions & 12 deletions frontend/src/renderer/components/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ import { isDialogOrMenuOpen } from "../lib/dom-selectors";
import { LOCAL_HOST } from "../lib/hosts";
import { isMacPlatform } from "../lib/platform";
import { revealSessionSearchMatch } from "../lib/session-search-reveal";
import { usePaletteSessionSearch, useSessionSearchIndexStatus } from "../hooks/usePaletteSessionSearch";
import { PALETTE_SESSION_SEARCH_LIMIT, usePaletteSessionSearch, useSessionSearchIndexStatus } from "../hooks/usePaletteSessionSearch";
import { useRemoteMachineSearch } from "../hooks/useRemoteMachineSearch";
import { machinesNotSearched, mergeMachineSearchResults, mergeNewestFirst } from "../lib/session-search-machines";
import { sessionReviewsQueryOptions, type PRReviewState } from "../lib/session-reviews";
import { spawnOrchestrator } from "../lib/spawn-orchestrator";
import { useShell } from "../lib/shell-context";
Expand Down Expand Up @@ -264,7 +266,39 @@ export const CommandPalette = memo(function CommandPalette() {
|| normalizedSessionQuery.length >= PALETTE_SESSION_SEARCH_MIN_CHARS);
const sessionSearchQuery = usePaletteSessionSearch(normalizedSessionQuery, LOCAL_HOST, sessionSearchEnabled);
const sessionSearchIndexStatus = useSessionSearchIndexStatus(LOCAL_HOST, isOpen && sessionSearchEnabled);
const sessionSearchHits = sessionSearchQuery.data?.results ?? [];
// The same words on every connected remote AO machine. This machine's answer
// shows at once; the merged list replaces it once every machine has answered
// or timed out, and never while this machine's answer still belongs to an
// earlier query. Recents (no words) stay this machine's.
const remoteSessionSearch = useRemoteMachineSearch(
{ query: normalizedSessionQuery, limit: PALETTE_SESSION_SEARCH_LIMIT },
sessionSearchEnabled,
);
const localSessionSearch = sessionSearchQuery.isPlaceholderData ? undefined : sessionSearchQuery.data;
// This machine's search finished and failed (its index is off or could not
// be opened). That is one machine not answering, not a pending answer: the
// machines that did answer still show, beside the local error notice.
const localSessionSearchFailed = sessionSearchQuery.isError && !sessionSearchQuery.isFetching;
const sessionSearchHits = useMemo(() => {
const local = sessionSearchQuery.data?.results ?? [];
const firstRemoteAnswer = remoteSessionSearch.answers.find((answer) => answer.outcome === "searched");
if (!remoteSessionSearch.settled || !firstRemoteAnswer) return local;
if (localSessionSearch) {
return mergeMachineSearchResults([
{ hostId: LOCAL_HOST, label: "", outcome: "searched", results: localSessionSearch.results ?? [], total: localSessionSearch.total ?? 0 },
...remoteSessionSearch.answers,
], mergeNewestFirst(localSessionSearch)).slice(0, PALETTE_SESSION_SEARCH_LIMIT);
}
if (localSessionSearchFailed) {
return mergeMachineSearchResults(remoteSessionSearch.answers, mergeNewestFirst(firstRemoteAnswer))
.slice(0, PALETTE_SESSION_SEARCH_LIMIT);
}
return local;
}, [sessionSearchQuery.data, localSessionSearch, localSessionSearchFailed, remoteSessionSearch]);
const sessionSearchMachinesNotSearched = useMemo(
() => (remoteSessionSearch.settled ? machinesNotSearched(remoteSessionSearch.answers, t) : []),
[remoteSessionSearch, t],
);

const sessionsWithOpenPRs = useMemo(
() =>
Expand Down Expand Up @@ -622,18 +656,24 @@ export const CommandPalette = memo(function CommandPalette() {
[],
);

const fileSessionRoute = useCallback((target: WorkspaceFileSearchTarget): NavigateTarget => {
if (target.hostId) {
return target.projectId === STANDALONE_WORKSPACE_ID
? { to: "/host/$hostId/session/$sessionId", params: { hostId: target.hostId, sessionId: target.sessionId } }
// A session on another machine opens on that machine's route.
const hostSessionRoute = useCallback((hostId: string | undefined, projectId: string, sessionId: string): NavigateTarget => {
if (hostId) {
return !projectId || projectId === STANDALONE_WORKSPACE_ID
? { to: "/host/$hostId/session/$sessionId", params: { hostId, sessionId } }
: {
to: "/host/$hostId/project/$projectId/session/$sessionId",
params: { hostId: target.hostId, projectId: target.projectId, sessionId: target.sessionId },
params: { hostId, projectId, sessionId },
};
}
return sessionRoute(target.projectId, target.sessionId);
return sessionRoute(projectId, sessionId);
}, [sessionRoute]);

const fileSessionRoute = useCallback(
(target: WorkspaceFileSearchTarget): NavigateTarget => hostSessionRoute(target.hostId, target.projectId, target.sessionId),
[hostSessionRoute],
);

const blockedByRestart = useCallback((projectId: string) => {
if (!useUiStore.getState().restartingProjectIds.has(projectId)) return false;
setError(t("command.orchestratorRestarting"));
Expand Down Expand Up @@ -823,9 +863,10 @@ export const CommandPalette = memo(function CommandPalette() {
case "open-search-result": {
// Hand the match to the session before navigating: the Chat
// timeline is mounted by the shell, so it picks the target up
// when it renders rather than from route state.
// when it renders rather than from route state. A session on
// another machine opens on that machine's route.
revealSessionSearchMatch(action);
navigateToTarget(sessionRoute(action.projectId, action.sessionId));
navigateToTarget(hostSessionRoute(action.hostId, action.projectId, action.sessionId));
Comment thread
illegalcall marked this conversation as resolved.
Resolved
closePalette();
break;
}
Expand Down Expand Up @@ -869,7 +910,7 @@ export const CommandPalette = memo(function CommandPalette() {
}
}
},
[daemonStatus.state, findChatWorkspace, navigate, navigateToTarget, closePalette, toggleTheme, openOrchestrator, resumeSession, pushView, blockedByRestart, openNewProject, queryClient, t, params.hostId, params.sessionId, fileSessionRoute, sessionRoute, workspaces],
[daemonStatus.state, findChatWorkspace, navigate, navigateToTarget, closePalette, toggleTheme, openOrchestrator, resumeSession, pushView, blockedByRestart, openNewProject, queryClient, t, params.hostId, params.sessionId, fileSessionRoute, hostSessionRoute, sessionRoute, workspaces],
);

const onSelectItem = useCallback(
Expand Down Expand Up @@ -1124,7 +1165,12 @@ export const CommandPalette = memo(function CommandPalette() {
))}
</CommandGroup>
))}
{sessionSearchEnabled && sessionSearchSettled && sessionSearchQuery.isFetching && (
{sessionSearchEnabled && sessionSearchSettled && sessionSearchMachinesNotSearched.length > 0 && (
<div role="status" className="px-[var(--size-command-pad-x)] py-2 text-caption text-muted-foreground" data-testid="palette-machines-not-searched">
{t("command.machinesNotSearched", { machines: sessionSearchMachinesNotSearched.join(", ") })}
</div>
)}
{sessionSearchEnabled && sessionSearchSettled && (sessionSearchQuery.isFetching || !remoteSessionSearch.settled) && (
<div role="status" className="px-[var(--size-command-pad-x)] py-2 text-caption text-muted-foreground">{t("command.searchingSessions")}</div>
)}
{/* An empty session-text result over an incomplete index is not the
Expand Down
Loading
Loading