Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: query memory leaks (#6889)

Peter Chinmana0ae74dadc18
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 038b1c5993..996c83193a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -75,6 +75,38 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
- Production web builds register `public/sw.js`: it serves the cached `index.html` and content-hashed assets from Cache Storage and moves tabs to newer builds. Set localStorage `macro:sw` to `off` to bypass it while debugging.
- The build fails if any emitted file exceeds CloudFront's 10 MB compression limit; split it rather than raising the limit.
+### Query callback lifetimes
+
+Query options can remain cached after their UI unmounts, including for disabled
+queries. Callbacks created inside hooks can retain component accessors, Solid
+owners, and detached DOM through shared closure environments—even when a callback
+only references a locally resolved ID. This does not mean every closure captures
+every local variable.
+
+- Create cached callbacks in module-scope query factories accepting resolved IDs,
+ flags, and plain data. Resolve reactive inputs inside the `useQuery` /
+ `useInfiniteQuery` options accessor, e.g. `useQuery(() => itemQueryOptions(id()))`,
+ so inputs still update reactively.
+- Keep pure selectors and polling policies at module scope, or inside those
+ factories. Check **all** retained callbacks: `queryFn`, `select`,
+ `refetchInterval`, pagination, placeholder callbacks, and functions in `meta`.
+- Do not pass component accessors, props getters, or query proxies into the
+ factory. For reactive selection, pass plain snapshots of the needed values
+ (such as channel names or a resolved document ID). Naming a function or copying
+ an ID inside the hook does not isolate its closure from the hook.
+- Use `keepPreviousData` from `@tanstack/solid-query` instead of an inline
+ `placeholderData: (p) => p`.
+- The same rule applies to callers of wrapper hooks such as `useSoupAstItemsQuery`
+ and `createGroupedSoupQueries`: `meta.itemFilter` / `meta.insertFilter` passed
+ from a component or view context are cached too, so build them with a
+ module-scope factory over plain snapshots (see
+ [drive-data-source](src/features/drive-view/queries/drive-data-source.ts)).
+- Query hooks in `src/lib/urql-solid` are exempt: their observers are created per
+ mount and destroyed on cleanup, so nothing outlives the component.
+
+Examples: [session query factory](src/lib/queries/agent-session/session.ts) and
+[search query factories](src/lib/queries/soup/search.ts).
+
### SolidJs
- Avoid createEffect. Legitimate uses: syncing with external/imperative systems (DOM APIs, third-party libs). If you're using it to derive state or trigger updates, use a derived signal or wrap the setter instead.
- Prefer wrapping the setter over `createEffect(() => { if (signal()) sideEffect() })`. When setting focus/selection should also clear another stop, blur a control, or scroll, put that work in the setter (or a named helper the setter calls) so the action is explicit at the call site — not a distant effect watching the signal.
diff --git a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
index 78c75a8177..f9b362aa27 100644
--- a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
+++ b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
@@ -15,9 +15,16 @@ import { notificationStateFromGraphql } from '@notifications/notification-state'
import { isUnreadChannelMessageNotification } from '@notifications/top-level-channel-notification';
import { createChannelUnreadQuery } from '@queries/channel/unread-presence';
import { makeGraphqlSoupInput } from '@queries/soup/graphql/ast';
-import { useSoupAstItemsQuery } from '@queries/soup/items';
+import {
+ type SoupApiItemFilter,
+ useSoupAstItemsQuery,
+} from '@queries/soup/items';
import { createMemo } from 'solid-js';
+// Module scope: cached query meta outlives the hook that registered it.
+const signalInsertFilter: SoupApiItemFilter = (item) =>
+ soupItemMatchesHomeTab(item, 'signal');
+
/** Presence in the loaded unread page, never a total or a pagination loop. */
export function useSidebarUnread() {
const notificationSource = useGlobalNotificationSource();
@@ -50,7 +57,7 @@ export function useSidebarUnread() {
facetContext: EMPTY_TAG_FACET_CONTEXT,
}),
() => ({
- meta: { insertFilter: (item) => soupItemMatchesHomeTab(item, 'signal') },
+ meta: { insertFilter: signalInsertFilter },
})
);
diff --git a/apps/web/src/features/block-pr/data/queries.ts b/apps/web/src/features/block-pr/data/queries.ts
index 06f3b603cc..b563e8cbdd 100644
--- a/apps/web/src/features/block-pr/data/queries.ts
+++ b/apps/web/src/features/block-pr/data/queries.ts
@@ -3,7 +3,7 @@ import { queryClient } from '@queries/client';
import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
import { storageServiceClient } from '@service-storage/client';
import type { StoredGithubPullRequest } from '@service-storage/generated/schemas/storedGithubPullRequest';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import type { PrRef } from '../util/prKey';
@@ -60,7 +60,7 @@ function prForeignEntityDataFromStored(
}
export function prForeignEntityQueryOptions(id: string) {
- return {
+ return queryOptions({
queryKey: prForeignEntityQueryKey(id),
queryFn: async (): Promise<PrForeignEntityData> =>
prForeignEntityDataFromStored(
@@ -70,7 +70,7 @@ export function prForeignEntityQueryOptions(id: string) {
),
staleTime: PR_STALE_TIME,
retry: 1,
- };
+ });
}
export function usePrForeignEntityQuery(id: Accessor<string>) {
diff --git a/apps/web/src/features/block-pr/views/PrDetail.test.ts b/apps/web/src/features/block-pr/views/PrDetail.test.ts
index e2656dbf3f..3d0f08b558 100644
--- a/apps/web/src/features/block-pr/views/PrDetail.test.ts
+++ b/apps/web/src/features/block-pr/views/PrDetail.test.ts
@@ -2,8 +2,7 @@ import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- invalidateQueries: vi.fn().mockResolvedValue(undefined),
- onRefreshed: undefined as (() => void) | undefined,
+ refreshedKeys: undefined as (() => readonly unknown[]) | undefined,
}));
vi.mock('../data/prDiscussionSource', () => ({
@@ -28,16 +27,12 @@ vi.mock('@entity/components/GithubLabelPill', () => ({
vi.mock('@notifications', () => ({
DebouncedNotificationReadMarker: () => null,
}));
-vi.mock('@tanstack/solid-query', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@tanstack/solid-query')>()),
- useQueryClient: () => ({ invalidateQueries: mocks.invalidateQueries }),
-}));
vi.mock('@queries/storage/github-pull-requests', () => ({
useRefreshGithubPullRequest: (
_reference: unknown,
- onRefreshed: () => void
+ refreshedKeys: () => readonly unknown[]
) => {
- mocks.onRefreshed = onRefreshed;
+ mocks.refreshedKeys = refreshedKeys;
},
}));
vi.mock('../data/queries', () => ({
@@ -57,19 +52,15 @@ vi.mock('../component/sidepanel/PrSidePanelSections', () => ({
import { githubPullRequestChangesKeys } from '@queries/storage/keys';
import { usePrDetail } from './PrDetail';
-describe('PR refresh cache invalidation', () => {
- it('invalidates the PR details and changes summary after a successful refresh', () => {
+describe('PR refresh wiring', () => {
+ it('passes the PR details and changes summary keys to the refresh', () => {
const id = '019a5faa-d2cd-7c55-8e8a-23aac4f0bc88';
createRoot((dispose) => {
usePrDetail(() => id);
- mocks.onRefreshed?.();
- expect(mocks.invalidateQueries).toHaveBeenCalledWith({
- queryKey: ['pr-foreign-entity', id],
- });
- expect(mocks.invalidateQueries).toHaveBeenCalledWith({
- queryKey: githubPullRequestChangesKeys.summary(id).queryKey,
- });
- expect(mocks.invalidateQueries).toHaveBeenCalledTimes(2);
+ expect(mocks.refreshedKeys?.()).toEqual([
+ ['pr-foreign-entity', id],
+ githubPullRequestChangesKeys.summary(id).queryKey,
+ ]);
dispose();
});
});
diff --git a/apps/web/src/features/block-pr/views/PrDetail.tsx b/apps/web/src/features/block-pr/views/PrDetail.tsx
index dba58fddc0..20846ce361 100644
--- a/apps/web/src/features/block-pr/views/PrDetail.tsx
+++ b/apps/web/src/features/block-pr/views/PrDetail.tsx
@@ -16,7 +16,6 @@ import {
useRefreshGithubPullRequest,
} from '@queries/storage/github-pull-requests';
import { githubPullRequestChangesKeys } from '@queries/storage/keys';
-import { useQueryClient } from '@tanstack/solid-query';
import { Button, cn, Layer, Scroll } from '@ui';
import { type Accessor, createMemo, Show, Suspense } from 'solid-js';
import { MergePullRequestButton } from '../component/MergePullRequestButton';
@@ -51,7 +50,6 @@ import { prDisplayName, prHtmlUrl } from '../util/prKey';
/** Share PR query state without coupling the host's header to the detail body. */
export function usePrDetail(foreignEntityId: Accessor<string>) {
- const queryClient = useQueryClient();
const query = usePrForeignEntityQuery(foreignEntityId);
// Detail-lifetime local Macro discussion (prototype-only, lost on reload).
const discussionSource = createPrDiscussionSource();
@@ -63,15 +61,6 @@ export function usePrDetail(foreignEntityId: Accessor<string>) {
? { additions: pullRequest.additions, deletions: pullRequest.deletions }
: undefined;
};
- const invalidateRefreshedPullRequest = async () => {
- const id = foreignEntityId();
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: prForeignEntityQueryKey(id) }),
- queryClient.invalidateQueries({
- queryKey: githubPullRequestChangesKeys.summary(id).queryKey,
- }),
- ]);
- };
useRefreshGithubPullRequest(
() => {
const pullRequest = data()?.pullRequest;
@@ -85,7 +74,13 @@ export function usePrDetail(foreignEntityId: Accessor<string>) {
url: pullRequest.url,
};
},
- () => void invalidateRefreshedPullRequest()
+ () => {
+ const id = foreignEntityId();
+ return [
+ prForeignEntityQueryKey(id),
+ githubPullRequestChangesKeys.summary(id).queryKey,
+ ];
+ }
);
return { query, data, discussionSource, changeCounts };
}
diff --git a/apps/web/src/features/block-project/component/Block.tsx b/apps/web/src/features/block-project/component/Block.tsx
index 69691e0971..ad66967625 100644
--- a/apps/web/src/features/block-project/component/Block.tsx
+++ b/apps/web/src/features/block-project/component/Block.tsx
@@ -24,6 +24,7 @@ import {
uploadFiles,
} from '@core/util/upload';
import { refetchSoupEntity } from '@queries/soup/cache';
+import type { SoupApiItem } from '@service-storage/generated/schemas';
import { refetchResources } from '@service-storage/util/refetchResources';
import { type Component, createSignal, Show } from 'solid-js';
import { useProjectScopedPanel } from './project-scoped-panel';
@@ -136,6 +137,13 @@ const Block: Component = () => {
);
};
+// Lands in cached soup query `meta`, so it is built over the plain id rather
+// than the component's props (see "Query callback lifetimes" in AGENTS.md).
+function projectMembershipFilter(projectId: string) {
+ return (item: SoupApiItem) =>
+ soupItemMatchesProjectMembership(item, projectId);
+}
+
type ProjectEntityListProps = {
scopeId: string;
projectId: string;
@@ -159,7 +167,7 @@ const ProjectEntityListContent = (props: ProjectEntityListProps) => {
itemMembershipFilter={
getIsSpecialProject(props.projectId)
? undefined
- : (item) => soupItemMatchesProjectMembership(item, props.projectId)
+ : projectMembershipFilter(props.projectId)
}
initialQuery={defineQueryFilters({
include: {
diff --git a/apps/web/src/features/crm/queries/companies.ts b/apps/web/src/features/crm/queries/companies.ts
index 4a2b7e2839..ff24bebbeb 100644
--- a/apps/web/src/features/crm/queries/companies.ts
+++ b/apps/web/src/features/crm/queries/companies.ts
@@ -5,13 +5,32 @@ import { soupKeys } from '@queries/soup/keys';
import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';
import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
-import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';
+import {
+ type QueryKey,
+ queryOptions,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
import type { CrmRecordDependencies } from './dependencies';
import { crmKeys } from './keys';
const COMPANY_STALE_TIME = 60 * 1000;
+function companyQueryOptions(deps: CrmRecordDependencies, companyId: string) {
+ return queryOptions({
+ queryKey: crmKeys.company(companyId).queryKey,
+ queryFn: () => {
+ if (!companyId) {
+ throw new Error('company id is required to fetch company');
+ }
+ return throwOnErr(() => deps.storage.getCompany({ companyId }));
+ },
+ staleTime: COMPANY_STALE_TIME,
+ enabled: !!companyId && companyId !== NIL_UUID,
+ });
+}
+
/** A contact row as embedded in the company response. */
export type CompanyContact = CrmContactResponse;
@@ -31,20 +50,7 @@ export function useCompanyQuery(
companyId: Accessor<string>
) {
const query = useQuery(
- () => {
- const id = companyId();
- return {
- queryKey: crmKeys.company(id).queryKey,
- queryFn: () => {
- if (!id) {
- throw new Error('company id is required to fetch company');
- }
- return throwOnErr(() => deps.storage.getCompany({ companyId: id }));
- },
- staleTime: COMPANY_STALE_TIME,
- enabled: !!companyId() && companyId() !== NIL_UUID,
- };
- },
+ () => companyQueryOptions(deps, companyId()),
() => deps.client
);
diff --git a/apps/web/src/features/crm/queries/contacts.ts b/apps/web/src/features/crm/queries/contacts.ts
index 4c5196245c..4e9daa13f4 100644
--- a/apps/web/src/features/crm/queries/contacts.ts
+++ b/apps/web/src/features/crm/queries/contacts.ts
@@ -49,6 +49,20 @@ export function useCrmContactByEmailQuery(
);
}
+function contactQueryOptions(deps: CrmRecordDependencies, contactId: string) {
+ return queryOptions({
+ queryKey: crmKeys.contact(contactId).queryKey,
+ queryFn: () => {
+ if (!contactId) {
+ throw new Error('contact id is required to fetch contact');
+ }
+ return throwOnErr(() => deps.storage.getContact({ contactId }));
+ },
+ staleTime: CONTACT_STALE_TIME,
+ enabled: !!contactId,
+ });
+}
+
/**
* Fetches a single CRM contact by id via `GET /crm/contacts/{id}`.
* The endpoint is role-aware: admins/owners see hidden contacts too,
@@ -60,20 +74,7 @@ export function useContactQuery(
contactId: Accessor<string>
) {
return useQuery(
- () => {
- const id = contactId();
- return {
- queryKey: crmKeys.contact(id).queryKey,
- queryFn: () => {
- if (!id) {
- throw new Error('contact id is required to fetch contact');
- }
- return throwOnErr(() => deps.storage.getContact({ contactId: id }));
- },
- staleTime: CONTACT_STALE_TIME,
- enabled: !!id,
- };
- },
+ () => contactQueryOptions(deps, contactId()),
() => deps.client
);
}
diff --git a/apps/web/src/features/crm/queries/lists.ts b/apps/web/src/features/crm/queries/lists.ts
index be438b5c15..5bb18d1de6 100644
--- a/apps/web/src/features/crm/queries/lists.ts
+++ b/apps/web/src/features/crm/queries/lists.ts
@@ -1,10 +1,20 @@
import { throwOnErr } from '@core/util/result';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { type CrmListConfig, isCrmListConfig } from '../core/navigation';
-import type { CrmQueryDependencies } from './dependencies';
+import type {
+ CrmQueryDependencies,
+ CrmRecordDependencies,
+} from './dependencies';
import { crmKeys } from './keys';
+function crmListsQueryOptions(deps: CrmRecordDependencies) {
+ return queryOptions({
+ queryKey: crmKeys.lists.queryKey,
+ queryFn: () => throwOnErr(() => deps.storage.views.getSavedViews()),
+ });
+}
+
/** Personal collections use saved-view storage, with explicit membership and team scope. */
export function useCrmLists(
deps: CrmQueryDependencies,
@@ -12,11 +22,7 @@ export function useCrmLists(
) {
const client = deps.client;
const query = useQuery(
- () => ({
- queryKey: crmKeys.lists.queryKey,
- queryFn: () => throwOnErr(() => deps.storage.views.getSavedViews()),
- enabled: !!teamId(),
- }),
+ () => ({ ...crmListsQueryOptions(deps), enabled: !!teamId() }),
() => deps.client
);
const lists = () =>
diff --git a/apps/web/src/features/crm/queries/saved-views.ts b/apps/web/src/features/crm/queries/saved-views.ts
index c4f9c54d62..520a557994 100644
--- a/apps/web/src/features/crm/queries/saved-views.ts
+++ b/apps/web/src/features/crm/queries/saved-views.ts
@@ -13,7 +13,7 @@ import type { CrmQueryDependencies } from './dependencies';
import { throwOnErr } from '@core/util/result';
import type { View } from '@service-storage/generated/schemas/view';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { createMemo } from 'solid-js';
import type { TeamConfigSource } from '../context/crm-sources';
@@ -29,6 +29,14 @@ export {
const CRM_SAVED_VIEWS_QUERY_KEY = ['crm', 'saved-views'] as const;
+function personalCrmViewsQueryOptions(deps: CrmQueryDependencies) {
+ return queryOptions({
+ queryKey: CRM_SAVED_VIEWS_QUERY_KEY,
+ queryFn: async () =>
+ await throwOnErr(async () => await deps.storage.views.getSavedViews()),
+ });
+}
+
export type PersonalCrmView = View & { config: CrmViewConfig };
/** Personal saved views (server-persisted via /saved_views). */
@@ -36,11 +44,7 @@ export function usePersonalCrmViews(deps: CrmQueryDependencies) {
const queryClient = deps.client;
const viewsQuery = useQuery(
- () => ({
- queryKey: CRM_SAVED_VIEWS_QUERY_KEY,
- queryFn: async () =>
- await throwOnErr(async () => await deps.storage.views.getSavedViews()),
- }),
+ () => personalCrmViewsQueryOptions(deps),
() => deps.client
);
diff --git a/apps/web/src/features/crm/queries/team-config.ts b/apps/web/src/features/crm/queries/team-config.ts
index a01372f8d1..91aefab946 100644
--- a/apps/web/src/features/crm/queries/team-config.ts
+++ b/apps/web/src/features/crm/queries/team-config.ts
@@ -26,20 +26,24 @@ export type {
import { throwOnErr } from '@core/util/result';
import type { CrmTeamSettingsResponse } from '@service-storage/generated/schemas/crmTeamSettingsResponse';
import type { UpdateCrmTeamSettingsRequest } from '@service-storage/generated/schemas/updateCrmTeamSettingsRequest';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import { createMemo } from 'solid-js';
export const CRM_TEAM_SETTINGS_QUERY_KEY = ['crm', 'team-settings'] as const;
+function teamCrmSettingsQueryOptions(deps: CrmQueryDependencies) {
+ return queryOptions({
+ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY,
+ queryFn: async () =>
+ await throwOnErr(() => deps.storage.getCrmTeamSettings()),
+ });
+}
+
export function useTeamCrmConfig(deps: CrmQueryDependencies) {
const queryClient = deps.client;
const settingsQuery = useQuery(
- () => ({
- queryKey: CRM_TEAM_SETTINGS_QUERY_KEY,
- queryFn: async () =>
- await throwOnErr(() => deps.storage.getCrmTeamSettings()),
- }),
+ () => teamCrmSettingsQueryOptions(deps),
() => deps.client
);
diff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsx
index 18d71dd011..a68b81e993 100644
--- a/apps/web/src/features/crm/workspace-adapter.tsx
+++ b/apps/web/src/features/crm/workspace-adapter.tsx
@@ -3,7 +3,7 @@ import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { useSettingsState } from '@core/constant/SettingsState';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { idToDisplayName } from '@core/user/util';
-import { isCrmCompanyEntity } from '@entity';
+import { type EntityData, isCrmCompanyEntity } from '@entity';
import { COMPANY_STAGE_OPTIONS } from '@entity/utils/task-properties';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { batch, createEffect, createRenderEffect, on } from 'solid-js';
@@ -18,11 +18,23 @@ import { createSoupViewState } from '../next-soup/soup-view/soup-view-context';
import { useSoupFilterPersistence } from '../next-soup/use-soup-filter-persistence';
import { openEntityInSplitFromUnifiedList } from '../next-soup/utils';
import type { CrmContext } from './context/crm-context';
+import type { DealStages } from './context/crm-sources';
import type { CrmWorkspace } from './context/workspace-context';
import type { CrmViewConfig } from './core/saved-view';
import { createCrmCollectionFilters } from './filter-adapter';
import { COMPANY_GROUP_OPTIONS } from './group-options';
+// The filter context lands in cached soup query meta, so its stage resolvers
+// close over the deal stages only, never this workspace's scope (see "Query
+// callback lifetimes" in apps/web/AGENTS.md).
+function stageFilterResolvers(stages: DealStages) {
+ return {
+ resolveCompanyStage: (entity: EntityData) =>
+ isCrmCompanyEntity(entity) ? stages.resolveStage(entity) : undefined,
+ companyStageLabel: stages.stageLabel,
+ };
+}
+
export function createCrmWorkspace(
crm: CrmContext,
sharedView?: CrmViewConfig
@@ -30,8 +42,7 @@ export function createCrmWorkspace(
const soup = useSoup();
const panel = useSplitPanelOrThrow();
const stages = crm.createDealStages();
- const resolveStage = (entity: import('@entity').EntityData) =>
- isCrmCompanyEntity(entity) ? stages.resolveStage(entity) : undefined;
+ const stageResolvers = stageFilterResolvers(stages);
const [persistFilters] = useSoupFilterPersistence();
const filters = createCrmCollectionFilters(crm, soup, persistFilters, stages);
const state = createSoupViewState({
@@ -41,7 +52,7 @@ export function createCrmWorkspace(
propertyGrouping: {
value: (entity, id) =>
id === SYSTEM_PROPERTY_IDS.STAGE
- ? (resolveStage(entity) ?? '')
+ ? (stageResolvers.resolveCompanyStage(entity) ?? '')
: undefined,
label: (value, id) =>
id === SYSTEM_PROPERTY_IDS.STAGE
@@ -55,8 +66,7 @@ export function createCrmWorkspace(
: COMPANY_STAGE_OPTIONS.map((option) => String(option.value)),
},
filterContext: () => ({
- resolveCompanyStage: resolveStage,
- companyStageLabel: stages.stageLabel,
+ ...stageResolvers,
owners: filters.state.ownerFilter(),
stages: filters.state.stageFilter(),
}),
diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.ts b/apps/web/src/features/drive-view/queries/drive-data-source.ts
index ec0ec631f0..08ab861554 100644
--- a/apps/web/src/features/drive-view/queries/drive-data-source.ts
+++ b/apps/web/src/features/drive-view/queries/drive-data-source.ts
@@ -13,7 +13,10 @@ import {
import { enableSnippets, isFeatureEnabled } from '@core/constant/featureFlags';
import type { EntityData } from '@entity';
import type { NotificationSource } from '@notifications';
-import { useSoupAstItemsQuery } from '@queries/soup/items';
+import {
+ type SoupApiItemFilter,
+ useSoupAstItemsQuery,
+} from '@queries/soup/items';
import {
isDisplayableSoupItem,
mapApiSoupItemToEntity,
@@ -33,6 +36,31 @@ import {
} from './drive-results';
import { buildDriveSearchRequest } from './drive-search';
+// Cached query meta outlives the view, so these filters are built at module
+// scope over plain snapshots and cannot retain the data source's scope.
+
+// REST inserts omit attachment status. Let a scoped server refetch admit them
+// rather than inserting an unverifiable document.
+function driveInsertFilter(current: DriveSelection): SoupApiItemFilter {
+ return (item) => current.scope === 'all' || item.tag !== 'document';
+}
+
+function driveItemFilter(
+ current: DriveSelection,
+ viewer: string | undefined,
+ context: ReturnType<typeof createTagFacetContext>
+): SoupApiItemFilter {
+ return (item) => {
+ if (!isDisplayableSoupItem(item)) return false;
+
+ const entity = mapApiSoupItemToEntity(item);
+
+ if (!driveEntityMatchesLocation(entity, current, viewer)) return false;
+
+ return testFacets(current.facets, DRIVE_FACETS, entity, context);
+ };
+}
+
/** Query, local/service search and row assembly owned by Drive. */
export function createDriveDataSource(options: {
selection: Accessor<DriveSelection>;
@@ -107,21 +135,8 @@ export function createDriveDataSource(options: {
? 'without-email'
: undefined,
meta: {
- // REST inserts omit attachment status. Let a scoped server refetch
- // admit them rather than inserting an unverifiable document.
- insertFilter: (item) =>
- current.scope === 'all' || item.tag !== 'document',
-
- itemFilter: (item) => {
- if (!isDisplayableSoupItem(item)) return false;
-
- const entity = mapApiSoupItemToEntity(item);
-
- if (!driveEntityMatchesLocation(entity, current, viewer))
- return false;
-
- return testFacets(current.facets, DRIVE_FACETS, entity, context);
- },
+ insertFilter: driveInsertFilter(current),
+ itemFilter: driveItemFilter(current, viewer, context),
},
};
}
diff --git a/apps/web/src/features/dynamic-ui/widgets/List.tsx b/apps/web/src/features/dynamic-ui/widgets/List.tsx
index 0d32ea04f9..0c9b32642f 100644
--- a/apps/web/src/features/dynamic-ui/widgets/List.tsx
+++ b/apps/web/src/features/dynamic-ui/widgets/List.tsx
@@ -15,6 +15,7 @@ import type { EntityData } from '@entity/types/entity';
import type { WithNotification } from '@entity/types/notification';
import type { GroupByField } from '@queries/soup/grouped/types';
import {
+ type SoupApiItemFilter,
type SoupAstItemsQueryArgs,
useSoupAstItemsQuery,
} from '@queries/soup/items';
@@ -104,6 +105,12 @@ const GROUP_BY_BY_NAME: Record<
project: { type: 'project' },
};
+// Cached query meta outlives the widget; the gate closes over the plain query
+// snapshot only, never the component scope.
+function queryItemFilter(source: Query): SoupApiItemFilter {
+ return (item) => soupItemMatchesQuery(item, source);
+}
+
/**
* One row: a real `ListEntity`, rendered flush the way SoupView / the unified
* list do. The row's own `Entity.Root` supplies its height, the rounded inset
@@ -158,10 +165,7 @@ function Rows(props: {
// normalized cache would prepend ANY optimistically/WS-inserted entity
// into it (a new task landing in an email-scoped list, etc.). Gate inserts
// on the same `Query` that produced the AST so only matching items appear.
- const source = query();
- return {
- meta: { itemFilter: (item) => soupItemMatchesQuery(item, source) },
- };
+ return { meta: { itemFilter: queryItemFilter(query()) } };
}
);
diff --git a/apps/web/src/features/entity/queries/email.ts b/apps/web/src/features/entity/queries/email.ts
index 520aa4e90f..c5624168f4 100644
--- a/apps/web/src/features/entity/queries/email.ts
+++ b/apps/web/src/features/entity/queries/email.ts
@@ -3,7 +3,7 @@ import { throwOnErr } from '@core/util/result';
import { emailClient } from '@service-email/client';
import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';
import type { PreviewsInboxCursorParams } from '@service-email/generated/schemas/previewsInboxCursorParams';
-import { useInfiniteQuery } from '@tanstack/solid-query';
+import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import type { EmailEntity } from '../types/entity';
@@ -28,6 +28,55 @@ const fetchPaginatedEmails = async ({
})
);
+type EmailPreviewPage = Awaited<ReturnType<typeof fetchPaginatedEmails>>;
+
+function selectEmailEntities(data: {
+ pages: EmailPreviewPage[];
+}): EmailEntity[] {
+ return data.pages.flatMap(({ items }) =>
+ items.map((email): EmailEntity => {
+ const participants = email.contacts.map((p) => ({
+ email: p.emailAddress ?? '',
+ name: p.name ?? '',
+ }));
+
+ return {
+ ...email,
+ type: 'email',
+ name: email.name || 'No Subject',
+ createdAt: email.createdAt,
+ updatedAt: email.updatedAt,
+ frecencyScore: email.frecencyScore ?? undefined,
+ viewedAt: email.viewedAt,
+ snippet: email.snippet ?? undefined,
+ isImportant: email.isImportant ?? false,
+ done: !email.inboxVisible,
+ participants,
+ senderEmail: email.senderEmail ?? undefined,
+ senderName: email.senderName ?? email.senderEmail ?? undefined,
+ };
+ })
+ );
+}
+
+// Cached callbacks only close over the resolved request params.
+function emailsInfiniteQueryOptions(
+ params: FetchPaginatedEmailsParams,
+ enabled: boolean,
+ refetchInterval: number | undefined
+) {
+ return infiniteQueryOptions({
+ queryKey: queryKeys.email({ infinite: true, ...params }),
+ queryFn: ({ pageParam }) => fetchPaginatedEmails(pageParam),
+ initialPageParam: params,
+ getNextPageParam: ({ next_cursor: cursor }) =>
+ cursor ? { ...params, cursor } : undefined,
+ select: selectEmailEntities,
+ enabled,
+ refetchInterval,
+ });
+}
+
export function createEmailsInfiniteQuery(
args?: Accessor<FetchPaginatedEmailsParams>,
options?: {
@@ -49,40 +98,11 @@ export function createEmailsInfiniteQuery(
};
};
- return useInfiniteQuery(() => {
- return {
- queryKey: queryKeys.email({ infinite: true, ...params() }),
- queryFn: ({ pageParam }) => fetchPaginatedEmails(pageParam),
- initialPageParam: params(),
- getNextPageParam: ({ next_cursor: cursor }) =>
- cursor ? { ...params(), cursor } : undefined,
- select: (data) =>
- data.pages.flatMap(({ items }) =>
- items.map((email): EmailEntity => {
- const participants = email.contacts.map((p) => ({
- email: p.emailAddress ?? '',
- name: p.name ?? '',
- }));
-
- return {
- ...email,
- type: 'email',
- name: email.name || 'No Subject',
- createdAt: email.createdAt,
- updatedAt: email.updatedAt,
- frecencyScore: email.frecencyScore ?? undefined,
- viewedAt: email.viewedAt,
- snippet: email.snippet ?? undefined,
- isImportant: email.isImportant ?? false,
- done: !email.inboxVisible,
- participants,
- senderEmail: email.senderEmail ?? undefined,
- senderName: email.senderName ?? email.senderEmail ?? undefined,
- };
- })
- ),
- enabled: !options?.disabled?.(),
- refetchInterval: options?.refetchInterval?.(),
- };
- });
+ return useInfiniteQuery(() =>
+ emailsInfiniteQueryOptions(
+ params(),
+ !options?.disabled?.(),
+ options?.refetchInterval?.()
+ )
+ );
}
diff --git a/apps/web/src/features/home/queries/use-home-query.ts b/apps/web/src/features/home/queries/use-home-query.ts
index 21a542f0ac..9dab531986 100644
--- a/apps/web/src/features/home/queries/use-home-query.ts
+++ b/apps/web/src/features/home/queries/use-home-query.ts
@@ -30,7 +30,10 @@ import {
} from '@entity';
import { unreadFilterFn } from '@entity/utils/filter';
import type { UnifiedNotification } from '@notifications/types';
-import { useSoupAstItemsQuery } from '@queries/soup/items';
+import {
+ type SoupApiItemFilter,
+ useSoupAstItemsQuery,
+} from '@queries/soup/items';
import { startOfDay, subWeeks } from 'date-fns';
import { createMemo, createSignal, onCleanup, onMount } from 'solid-js';
import { match } from 'ts-pattern';
@@ -109,6 +112,12 @@ function matchesTab(
.exhaustive();
}
+// Cached query meta outlives the view; build the gate at module scope over the
+// plain tab value so it cannot retain this hook's scope.
+function homeTabInsertFilter(tab: HomeTab): SoupApiItemFilter {
+ return (item) => soupItemMatchesHomeTab(item, tab);
+}
+
/** Shared feed membership for the Home list and its sidebar unread indicator. */
export function useHomeEntitiesQuery(
state: Pick<HomeDataSourceInput, 'tab' | 'facets'>
@@ -149,7 +158,7 @@ export function useHomeEntitiesQuery(
enabled: true,
showSupportedForeignEntities: foreignEntities().enabled,
meta: {
- insertFilter: (item) => soupItemMatchesHomeTab(item, tab),
+ insertFilter: homeTabInsertFilter(tab),
},
};
});
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.mount.test.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.mount.test.tsx
new file mode 100644
index 0000000000..0ba14b4bf1
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.mount.test.tsx
@@ -0,0 +1,157 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SoupViewContextProvider } from './soup-view-context';
+
+// The provider builds its query options during setup. solid-query evaluates an
+// options accessor synchronously inside the hook call (createMemo), so anything
+// the accessor reads must already be declared. These mocks keep that eager
+// evaluation while stubbing the network-backed queries.
+const mocks = vi.hoisted(() => {
+ // jsdom's WebSocket delegates to `ws`, which refuses to run in a browser
+ // environment; app-shell singletons open one at import time.
+ class FakeWebSocket {
+ readyState = 1;
+ close() {}
+ send() {}
+ addEventListener() {}
+ removeEventListener() {}
+ }
+ vi.stubGlobal('WebSocket', FakeWebSocket);
+ return {
+ itemsOptionsEvaluated: vi.fn(),
+ groupedOptionsEvaluated: vi.fn(),
+ searchOptionsEvaluated: vi.fn(),
+ };
+});
+
+vi.mock('@queries/soup/items', () => ({
+ useSoupAstItemsQuery: (
+ args: () => unknown,
+ options?: () => { meta?: unknown }
+ ) => {
+ args();
+ mocks.itemsOptionsEvaluated(options?.());
+ return {
+ transport: 'rest',
+ data: undefined,
+ error: null,
+ isLoading: false,
+ isFetching: false,
+ isFetchingNextPage: false,
+ isPlaceholderData: false,
+ isEnabled: () => true,
+ hasNextPage: false,
+ fetchNextPage: vi.fn(),
+ refresh: vi.fn(),
+ resetToInitialPage: vi.fn(),
+ };
+ },
+}));
+
+vi.mock('@queries/soup/grouped/create-grouped-soup-queries', () => ({
+ createGroupedSoupQueries: (args: {
+ groupByField: () => unknown;
+ initialPage: () => unknown;
+ soupParams: () => unknown;
+ soupBody: () => unknown;
+ transport: () => unknown;
+ queryOptions: () => { meta?: unknown };
+ }) => {
+ args.groupByField();
+ args.initialPage();
+ args.soupParams();
+ args.soupBody();
+ args.transport();
+ mocks.groupedOptionsEvaluated(args.queryOptions());
+ return { map: () => new Map(), resetToInitialPage: vi.fn() };
+ },
+}));
+
+vi.mock('@queries/soup/search', () => ({
+ validateSearchServiceText: () => false,
+ useSearchSoupQuery: (args: () => unknown, options?: () => unknown) => {
+ args();
+ mocks.searchOptionsEvaluated(options?.());
+ return {
+ data: undefined,
+ error: null,
+ isLoading: false,
+ isFetching: false,
+ isFetchingNextPage: false,
+ hasNextPage: false,
+ fetchNextPage: vi.fn(),
+ };
+ },
+}));
+vi.mock('@app/features/soup/search', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useSearchContext: () => ({ entityPool: () => [] }),
+ useOptionalSearchContext: () => ({ entityPool: () => [] }),
+}));
+vi.mock('@queries/properties/tags', () => ({
+ useTagsQuery: () => ({ data: [], isSuccess: true }),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { send() {}, addEventListener() {}, removeEventListener() {} },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect() {},
+ createConnectionWebsocketEffect() {},
+ parseWebsocketPayload: () => undefined,
+}));
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useSplitPanelOrThrow: () => ({
+ handle: {
+ id: 'panel-1',
+ isActive: () => true,
+ content: () => ({ type: 'component', id: 'home' }),
+ currentEntryState: () => undefined,
+ registerEntryStateCaptor: () => () => {},
+ },
+ }),
+}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-1' }));
+vi.mock('@components/app/GlobalAppState', () => ({
+ useGlobalNotificationSource: () => ({}),
+}));
+vi.mock('@queries/team/teams', () => ({ useIsTeamAdmin: () => () => false }));
+vi.mock('@app/features/next-soup/use-soup-filter-persistence', () => ({
+ useSoupFilterPersistence: () => [vi.fn()],
+}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: false }),
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('SoupViewContextProvider setup', () => {
+ it('mounts with query options evaluated synchronously during setup', () => {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ render(() => (
+ <QueryClientProvider client={client}>
+ <SoupViewContextProvider>
+ <div data-testid="child">ready</div>
+ </SoupViewContextProvider>
+ </QueryClientProvider>
+ ));
+
+ expect(screen.getByTestId('child').textContent).toBe('ready');
+ expect(mocks.itemsOptionsEvaluated).toHaveBeenCalledTimes(1);
+ expect(mocks.groupedOptionsEvaluated).toHaveBeenCalledTimes(1);
+ expect(mocks.searchOptionsEvaluated).toHaveBeenCalledTimes(1);
+ expect(mocks.searchOptionsEvaluated).toHaveBeenCalledWith({
+ enabled: false,
+ });
+ const meta = mocks.itemsOptionsEvaluated.mock.calls[0]?.[0]?.meta as {
+ itemFilter?: unknown;
+ insertFilter?: unknown;
+ };
+ expect(typeof meta.itemFilter).toBe('function');
+ expect(typeof meta.insertFilter).toBe('function');
+ });
+});
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
index 47cfbfef94..f7199f7958 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
@@ -2,8 +2,6 @@ import {
entityMatchesTagFilter,
isListViewID,
type ListView,
- soupItemMatchesListView,
- soupItemMatchesTagFilter,
} from '@app/constants/list-views';
import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';
import {
@@ -15,7 +13,6 @@ import {
type SoupState,
} from '@app/features/next-soup/create-soup-state';
import type { FilterContext } from '@app/features/next-soup/filters/configs/';
-import { emailItemMatchesImportance } from '@app/features/next-soup/filters/email-signal';
import {
compileToAst,
NIL_UUID,
@@ -39,6 +36,13 @@ import {
import { dateBucket } from '@app/features/next-soup/soup-view/group-by-date';
import { INBOX_FILTER_ENTRY_KEY } from '@app/features/next-soup/soup-view/inbox-filter-controllers';
import { SORT_CONFIGS } from '@app/features/next-soup/soup-view/sort-options';
+import {
+ createSoupViewItemFilter,
+ emailImportanceInsertFilter,
+ entityMatchesReadFilter,
+ type ReadFilter,
+ type SoupViewItemFilterSnapshot,
+} from '@app/features/next-soup/soup-view/soup-view-item-filter';
import { useSoupFilterPersistence } from '@app/features/next-soup/use-soup-filter-persistence';
import { deduplicateEntities } from '@app/features/next-soup/utils';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
@@ -79,10 +83,6 @@ import type {
import type { SoupParams } from '@queries/soup/items';
import { useSoupAstItemsQuery } from '@queries/soup/items';
import { soupKeys } from '@queries/soup/keys';
-import {
- isDisplayableSoupItem,
- mapApiSoupItemToEntity,
-} from '@queries/soup/transform-utils';
import { useIsTeamAdmin } from '@queries/team/teams';
import type { SoupApiItem } from '@service-storage/generated/schemas';
import { makePersisted } from '@solid-primitives/storage';
@@ -102,10 +102,7 @@ import {
useContext,
} from 'solid-js';
import { unwrap } from 'solid-js/store';
-import {
- applyDocumentTabScope,
- withDocumentTabItemScope,
-} from './document-tab-scope';
+import { applyDocumentTabScope } from './document-tab-scope';
import { resolveInitialViewFilters } from './initial-view-filters';
type DataSource<T> = {
@@ -162,7 +159,7 @@ type SoupViewInitializeOptions = {
itemMembershipFilter?: (item: SoupApiItem) => boolean;
};
-export type ReadFilter = 'all' | 'unread' | 'read';
+export type { ReadFilter };
/** List/board display mode — currently only the Customers view offers a board. */
export type SoupViewMode = 'list' | 'board';
@@ -776,22 +773,6 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
};
};
- // A row the status filter admitted stays admitted for the rest of the visit
- // (see `admittedByStatusFilter`). The inbox opens rows in a preview pane, and
- // previewing marks the row read — so without this the row the user just
- // clicked drops out from under the preview they are still reading, taking the
- // list position with it. The row re-renders in its read styling, it just keeps
- // its place.
- const entityMatchesInboxReadFilter = (entity: EntityData): boolean => {
- const filter = readFilter();
- if (filter === 'all' || !isHomeView()) return true;
- const isUnread = unreadFilterFn(entity);
- return (
- (filter === 'unread' ? isUnread : !isUnread) ||
- admittedByStatusFilter().ids.has(entity.id)
- );
- };
-
const applyViewFilters = (state: QueryState): QueryState => {
let next = applyInboxFilter(state);
next = applyInboxThreadFilter(next);
@@ -911,32 +892,28 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
const activeTagFilterMode = () =>
queryFilters.state.include.tagFilterMode ?? 'any';
- const soupItemMatchesActiveFilters = (
- item: SoupApiItem,
- view: ListView | undefined
- ): boolean => {
- if (!soupItemMatchesListView(item, view)) return false;
-
- if (
- !soupItemMatchesTagFilter(
- item,
- activeTagOptionIds(),
- activeTagFilterMode()
- )
- ) {
- return false;
- }
-
- const membershipFilter = config().itemMembershipFilter;
- if (membershipFilter && !membershipFilter(item)) return false;
+ // Live, not snapshotted: the cache membership filter reads `.current` when it
+ // runs. Declared before the query hooks below, whose options accessors run
+ // synchronously at setup. Written by `admittedByStatusFilter` once it exists.
+ const admittedIds: { current: ReadonlySet<string> } = { current: new Set() };
- if (!isDisplayableSoupItem(item)) return false;
- const entity = mapApiSoupItemToEntity(item) as SoupEntity;
- return (
- soup.predicates.test(entity, getFilterContext()) &&
- entityMatchesInboxReadFilter(entity)
- );
- };
+ // Everything else the cache membership filter needs, read at options time so
+ // the options accessor tracks it. The filter itself is built at module scope
+ // so the cached query never retains this provider's scope.
+ const itemFilterSnapshot = (
+ view: ListView | undefined
+ ): SoupViewItemFilterSnapshot => ({
+ view,
+ tab: view === 'documents' ? activeTab() : undefined,
+ userId: userId(),
+ tagOptionIds: activeTagOptionIds(),
+ tagFilterMode: activeTagFilterMode(),
+ membershipFilter: config().itemMembershipFilter,
+ testPredicates: soup.predicates.test,
+ filterContext: getFilterContext(),
+ readFilter: readFilter(),
+ admittedIds,
+ });
// The Soup query facade owns GraphQL eligibility and REST fallback. Its urql
// implementation keeps loaded pages subscribed to the normalized cache.
@@ -960,13 +937,8 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,
onBeforeGraphqlRefresh: () => groupQueries.resetToInitialPage(),
meta: {
- itemFilter: withDocumentTabItemScope(
- view === 'documents' ? activeTab() : undefined,
- userId(),
- (item) => soupItemMatchesActiveFilters(item, view)
- ),
- insertFilter: (item) =>
- emailItemMatchesImportance(item, emailImportance),
+ itemFilter: createSoupViewItemFilter(itemFilterSnapshot(view)),
+ insertFilter: emailImportanceInsertFilter(emailImportance),
},
};
}
@@ -1083,13 +1055,15 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
);
// Ids that have matched the inbox status filter at some point during this
- // visit, so `entityMatchesInboxReadFilter` can keep admitting a row after the
- // user reads it.
+ // visit, so `entityMatchesReadFilter` can keep admitting a row after the user
+ // reads it.
//
// A visit is one view/tab/filter combination: changing any of them starts a
// new set, and returning a new object is what re-runs every consumer. An
// effect that emptied the set in place would not — a plain Set notifies
// nothing — and the list would keep rendering the previous visit's rows.
+ // The memo also publishes the set to `admittedIds`, so the cache membership
+ // filter reads it without holding this provider's reactive graph.
const admittedByStatusFilter = createMemo<{
scope: string;
ids: Set<string>;
@@ -1105,6 +1079,7 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
}
}
+ admittedIds.current = ids;
return { scope, ids };
});
@@ -1113,13 +1088,20 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
const ctx = getFilterContext();
const tagOptionIds = activeTagOptionIds();
const tagFilterMode = activeTagFilterMode();
+ const statusFilter = readFilter();
+ const homeView = isHomeView();
+ // Only an active status filter on Home consults the admitted rows.
+ const admitted =
+ statusFilter !== 'all' && homeView
+ ? admittedByStatusFilter().ids
+ : new Set<string>();
const next = [];
for (const entity of transformed) {
if (!soup.predicates.test(entity, ctx)) {
continue;
}
- if (!entityMatchesInboxReadFilter(entity)) {
+ if (!entityMatchesReadFilter(entity, statusFilter, homeView, admitted)) {
continue;
}
if (!entityMatchesTagFilter(entity, tagOptionIds, tagFilterMode)) {
@@ -1184,13 +1166,8 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {
return {
enabled: enabled() && !search.isSearching(),
meta: {
- itemFilter: withDocumentTabItemScope(
- view === 'documents' ? activeTab() : undefined,
- userId(),
- (item) => soupItemMatchesActiveFilters(item, view)
- ),
- insertFilter: (item) =>
- emailItemMatchesImportance(item, emailImportance),
+ itemFilter: createSoupViewItemFilter(itemFilterSnapshot(view)),
+ insertFilter: emailImportanceInsertFilter(emailImportance),
},
};
},
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-item-filter.ts b/apps/web/src/features/next-soup/soup-view/soup-view-item-filter.ts
new file mode 100644
index 0000000000..712cf6767c
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-item-filter.ts
@@ -0,0 +1,102 @@
+import {
+ type ListView,
+ soupItemMatchesListView,
+ soupItemMatchesTagFilter,
+} from '@app/constants/list-views';
+import type { SoupEntity } from '@app/features/next-soup/create-soup-state';
+import type { FilterContext } from '@app/features/next-soup/filters/configs/';
+import { emailItemMatchesImportance } from '@app/features/next-soup/filters/email-signal';
+import type { TagFilterMode } from '@app/features/next-soup/filters/filter-store/types';
+import { type EntityData, unreadFilterFn } from '@entity';
+import type { SoupApiItemFilter } from '@queries/soup/items';
+import {
+ isDisplayableSoupItem,
+ mapApiSoupItemToEntity,
+} from '@queries/soup/transform-utils';
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import { withDocumentTabItemScope } from './document-tab-scope';
+
+// The functions built here land in cached query `meta`, which TanStack keeps
+// for gcTime after the soup view unmounts. They are created at module scope
+// over plain snapshots so the cache never retains the view provider's scope
+// (see "Query callback lifetimes" in apps/web/AGENTS.md).
+
+export type ReadFilter = 'all' | 'unread' | 'read';
+
+/**
+ * A row the status filter admitted stays admitted for the rest of the visit
+ * (`admittedIds`). The inbox opens rows in a preview pane, and previewing
+ * marks the row read, so without this the row the user just clicked would
+ * drop out from under the preview they are still reading.
+ */
+export function entityMatchesReadFilter(
+ entity: EntityData,
+ filter: ReadFilter,
+ isHomeView: boolean,
+ admittedIds: ReadonlySet<string>
+): boolean {
+ if (filter === 'all' || !isHomeView) return true;
+ const isUnread = unreadFilterFn(entity);
+ return (
+ (filter === 'unread' ? isUnread : !isUnread) || admittedIds.has(entity.id)
+ );
+}
+
+export type SoupViewItemFilterSnapshot = {
+ view: ListView | undefined;
+ /** Documents tab when the view is Documents; scopes cache membership. */
+ tab: string | undefined;
+ userId: string | undefined;
+ tagOptionIds: readonly string[];
+ tagFilterMode: TagFilterMode;
+ /** Caller-supplied membership gate (a project block scopes to its project). */
+ membershipFilter: SoupApiItemFilter | undefined;
+ /** The soup state's predicate store test; reads the live predicate ids. */
+ testPredicates: (entity: SoupEntity, ctx: FilterContext) => boolean;
+ filterContext: FilterContext;
+ readFilter: ReadFilter;
+ /** Live view of the ids the status filter has admitted this visit. */
+ admittedIds: { readonly current: ReadonlySet<string> };
+};
+
+/** Cache membership for one soup view query: does an item belong in it? */
+export function createSoupViewItemFilter(
+ snapshot: SoupViewItemFilterSnapshot
+): SoupApiItemFilter {
+ const matches = (item: SoupApiItem): boolean => {
+ if (!soupItemMatchesListView(item, snapshot.view)) return false;
+
+ if (
+ !soupItemMatchesTagFilter(
+ item,
+ snapshot.tagOptionIds,
+ snapshot.tagFilterMode
+ )
+ ) {
+ return false;
+ }
+
+ if (snapshot.membershipFilter && !snapshot.membershipFilter(item))
+ return false;
+
+ if (!isDisplayableSoupItem(item)) return false;
+ const entity = mapApiSoupItemToEntity(item) as SoupEntity;
+ return (
+ snapshot.testPredicates(entity, snapshot.filterContext) &&
+ entityMatchesReadFilter(
+ entity,
+ snapshot.readFilter,
+ snapshot.view === 'home',
+ snapshot.admittedIds.current
+ )
+ );
+ };
+ return withDocumentTabItemScope(snapshot.tab, snapshot.userId, matches);
+}
+
+/** Websocket-insert gate for importance tabs; see `emailItemMatchesImportance`. */
+export function emailImportanceInsertFilter(
+ emailImportance: boolean | undefined
+): SoupApiItemFilter {
+ return (item) => emailItemMatchesImportance(item, emailImportance);
+}
diff --git a/apps/web/src/features/routines/queries/schedules.ts b/apps/web/src/features/routines/queries/schedules.ts
index b8c76c7167..02f9dead54 100644
--- a/apps/web/src/features/routines/queries/schedules.ts
+++ b/apps/web/src/features/routines/queries/schedules.ts
@@ -8,7 +8,12 @@ import type {
ScheduledAction,
UpdateScheduledAction,
} from '@service-scheduled-action/generated/schemas';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import {
+ keepPreviousData,
+ queryOptions,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { scheduledActionKeys } from './keys';
@@ -64,40 +69,45 @@ function patchScheduleEnabled(scheduleId: string, enabled: boolean) {
);
}
+function fetchSchedules() {
+ return throwOnErr(async () => await scheduledActionClient.listSchedules());
+}
+
export function useSchedulesQuery(enabled: Accessor<boolean>) {
return useQuery(() => ({
queryKey: scheduledActionKeys.list.queryKey,
enabled: enabled(),
- queryFn: async () =>
- throwOnErr(async () => await scheduledActionClient.listSchedules()),
- placeholderData: (prev: ScheduledAction[] | undefined) => prev,
+ queryFn: fetchSchedules,
+ placeholderData: keepPreviousData,
reconcile: 'id',
...QUERY_REFETCH_BEHAVIOR,
}));
}
+// Cached past unmount; closes over the resolved schedule id only.
+function scheduleHistoryQueryOptions(
+ scheduleId: string | null | undefined,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: scheduledActionKeys.history({
+ scheduleId: scheduleId ?? '__none__',
+ }).queryKey,
+ enabled: enabled && Boolean(scheduleId),
+ queryFn: async () =>
+ throwOnErr(
+ async () =>
+ await scheduledActionClient.listHistory({ scheduleId: scheduleId! })
+ ),
+ ...QUERY_REFETCH_BEHAVIOR,
+ });
+}
+
export function useScheduleHistoryQuery(
scheduleId: Accessor<string | null | undefined>,
enabled: Accessor<boolean>
) {
- return useQuery(() => {
- const currentScheduleId = scheduleId();
-
- return {
- queryKey: scheduledActionKeys.history({
- scheduleId: currentScheduleId ?? '__none__',
- }).queryKey,
- enabled: enabled() && Boolean(currentScheduleId),
- queryFn: async () =>
- throwOnErr(
- async () =>
- await scheduledActionClient.listHistory({
- scheduleId: currentScheduleId!,
- })
- ),
- ...QUERY_REFETCH_BEHAVIOR,
- };
- });
+ return useQuery(() => scheduleHistoryQueryOptions(scheduleId(), enabled()));
}
export function invalidateSchedules() {
diff --git a/apps/web/src/lib/queries/agent-repositories/branches.ts b/apps/web/src/lib/queries/agent-repositories/branches.ts
index 2cb8eb4b77..65cfa4e9a6 100644
--- a/apps/web/src/lib/queries/agent-repositories/branches.ts
+++ b/apps/web/src/lib/queries/agent-repositories/branches.ts
@@ -1,6 +1,6 @@
import { throwOnErr } from '@core/util/result';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import { agentRepositoryKeys } from './keys';
/**
@@ -14,16 +14,15 @@ import { agentRepositoryKeys } from './keys';
export function useAgentRepositoryBranchesQuery(
repoUrl: () => string | undefined
) {
- return useQuery(() => {
- const url = repoUrl();
- return {
- queryKey: agentRepositoryKeys.branches(url ?? '').queryKey,
- queryFn: async () =>
- throwOnErr(() =>
- agentHarnessServiceClient.listRepositoryBranches(url ?? '')
- ),
- enabled: !!url,
- staleTime: 2 * 60 * 1000,
- };
+ return useQuery(() => agentRepositoryBranchesQueryOptions(repoUrl() ?? ''));
+}
+
+function agentRepositoryBranchesQueryOptions(url: string) {
+ return queryOptions({
+ queryKey: agentRepositoryKeys.branches(url).queryKey,
+ queryFn: () =>
+ throwOnErr(() => agentHarnessServiceClient.listRepositoryBranches(url)),
+ enabled: !!url,
+ staleTime: 2 * 60 * 1000,
});
}
diff --git a/apps/web/src/lib/queries/agent-repositories/repositories.ts b/apps/web/src/lib/queries/agent-repositories/repositories.ts
index 95affdbad1..26eba2c314 100644
--- a/apps/web/src/lib/queries/agent-repositories/repositories.ts
+++ b/apps/web/src/lib/queries/agent-repositories/repositories.ts
@@ -3,6 +3,10 @@ import { agentHarnessServiceClient } from '@service-agent-harness/client';
import { useQuery } from '@tanstack/solid-query';
import { agentRepositoryKeys } from './keys';
+function fetchAgentRepositories() {
+ return throwOnErr(() => agentHarnessServiceClient.listRepositories());
+}
+
/**
* The GitHub repositories the signed-in user can hand a coding session: every
* repository under an installation of Macro's GitHub App they or their teams
@@ -16,8 +20,7 @@ import { agentRepositoryKeys } from './keys';
export function useAgentRepositoriesQuery(enabled: () => boolean = () => true) {
return useQuery(() => ({
queryKey: agentRepositoryKeys.list.queryKey,
- queryFn: async () =>
- throwOnErr(() => agentHarnessServiceClient.listRepositories()),
+ queryFn: fetchAgentRepositories,
enabled: enabled(),
staleTime: 5 * 60 * 1000,
}));
diff --git a/apps/web/src/lib/queries/agent-session/changes.ts b/apps/web/src/lib/queries/agent-session/changes.ts
index 44b6630501..e28775ed58 100644
--- a/apps/web/src/lib/queries/agent-session/changes.ts
+++ b/apps/web/src/lib/queries/agent-session/changes.ts
@@ -10,7 +10,7 @@
import { throwOnErr } from '@core/util/result';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { invalidateAgentSessionChanges } from './changes-sync';
import { agentSessionChangesKeys } from './keys';
@@ -22,22 +22,38 @@ import { agentSessionChangesKeys } from './keys';
*/
export const CAPTURE_POLL_INTERVAL_MS = 3_000;
+// Cached callbacks close over the resolved id only, never the accessor.
+function agentSessionChangesQueryOptions(id: string | undefined) {
+ return queryOptions({
+ queryKey: agentSessionChangesKeys.summary(id ?? '').queryKey,
+ queryFn: () => throwOnErr(() => agentHarnessServiceClient.getChanges(id!)),
+ enabled: Boolean(id),
+ retry: false,
+ staleTime: 30_000,
+ refetchInterval: (query) =>
+ query.state.data?.capturing ? CAPTURE_POLL_INTERVAL_MS : false,
+ });
+}
+
/** The session's latest changes summary. Disabled while `sessionId` is unset. */
export function useAgentSessionChangesQuery(
sessionId: Accessor<string | undefined>
) {
- return useQuery(() => {
- const id = sessionId();
- return {
- queryKey: agentSessionChangesKeys.summary(id ?? '').queryKey,
- queryFn: () =>
- throwOnErr(() => agentHarnessServiceClient.getChanges(id!)),
- enabled: Boolean(id),
- retry: false,
- staleTime: 30_000,
- refetchInterval: (query) =>
- query.state.data?.capturing ? CAPTURE_POLL_INTERVAL_MS : false,
- };
+ return useQuery(() => agentSessionChangesQueryOptions(sessionId()));
+}
+
+function agentSessionChangesPatchQueryOptions(
+ id: string | undefined,
+ changeset: string | undefined
+) {
+ return queryOptions({
+ queryKey: agentSessionChangesKeys.patch(id ?? '', changeset ?? '').queryKey,
+ queryFn: () =>
+ throwOnErr(() => agentHarnessServiceClient.getChangesPatch(id!)),
+ enabled: Boolean(id) && Boolean(changeset),
+ retry: 1,
+ // A changeset's body never changes once captured.
+ staleTime: Number.POSITIVE_INFINITY,
});
}
@@ -50,20 +66,9 @@ export function useAgentSessionChangesPatchQuery(
sessionId: Accessor<string | undefined>,
changesetId: Accessor<string | undefined>
) {
- return useQuery(() => {
- const id = sessionId();
- const changeset = changesetId();
- return {
- queryKey: agentSessionChangesKeys.patch(id ?? '', changeset ?? '')
- .queryKey,
- queryFn: () =>
- throwOnErr(() => agentHarnessServiceClient.getChangesPatch(id!)),
- enabled: Boolean(id) && Boolean(changeset),
- retry: 1,
- // A changeset's body never changes once captured.
- staleTime: Number.POSITIVE_INFINITY,
- };
- });
+ return useQuery(() =>
+ agentSessionChangesPatchQueryOptions(sessionId(), changesetId())
+ );
}
/**
diff --git a/apps/web/src/lib/queries/agent-session/mentions.ts b/apps/web/src/lib/queries/agent-session/mentions.ts
index 87256377ab..13499added 100644
--- a/apps/web/src/lib/queries/agent-session/mentions.ts
+++ b/apps/web/src/lib/queries/agent-session/mentions.ts
@@ -1,6 +1,6 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableGraphqlSoup } from '@core/constant/featureFlags';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { agentSessionKeys } from './keys';
import { createAgentSessionMentionBatcher } from './mention-batcher';
@@ -13,15 +13,25 @@ const graphqlPreview = createAgentSessionMentionBatcher((ids) =>
fetchAgentSessionMentionPreviews(ids, true)
);
+function agentSessionMentionQueryOptions(
+ id: string,
+ graphql: boolean,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: agentSessionKeys.preview(id, graphql).queryKey,
+ queryFn: () => (graphql ? graphqlPreview : restPreview)(id),
+ enabled: enabled && !!id,
+ staleTime: 15_000,
+ });
+}
+
export function useAgentSessionMentionPreview(
id: Accessor<string>,
enabled: Accessor<boolean>
) {
const flag = useFeatureFlag(enableGraphqlSoup);
- return useQuery(() => ({
- queryKey: agentSessionKeys.preview(id(), flag().enabled).queryKey,
- queryFn: () => (flag().enabled ? graphqlPreview : restPreview)(id()),
- enabled: enabled() && !!id(),
- staleTime: 15_000,
- }));
+ return useQuery(() =>
+ agentSessionMentionQueryOptions(id(), flag().enabled, enabled())
+ );
}
diff --git a/apps/web/src/lib/queries/agent-session/session.ts b/apps/web/src/lib/queries/agent-session/session.ts
index 084212a481..4f77cd2bcb 100644
--- a/apps/web/src/lib/queries/agent-session/session.ts
+++ b/apps/web/src/lib/queries/agent-session/session.ts
@@ -12,7 +12,7 @@
import { throwOnErr } from '@core/util/result';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { agentSessionKeys } from './keys';
@@ -38,37 +38,37 @@ export const EXTERNAL_URL_POLL_ATTEMPTS = 15;
export function useAgentSessionExternalUrlQuery(
sessionId: Accessor<string | undefined>
) {
- return useQuery(() => {
- const id = sessionId();
- return {
- queryKey: ['agentSession', 'externalUrl', id ?? ''] as const,
- queryFn: async () =>
- await throwOnErr(() => agentHarnessServiceClient.get(id!)),
- enabled: Boolean(id),
- // Stop once the url lands or the attempt budget is spent. Failed
- // fetches count too, so a streak of errors cannot poll forever.
- refetchInterval: (query) => {
- if (query.state.data?.external?.url) return false;
- const attempts =
- query.state.dataUpdateCount + query.state.errorUpdateCount;
- if (attempts >= EXTERNAL_URL_POLL_ATTEMPTS) return false;
- return EXTERNAL_URL_POLL_INTERVAL_MS;
- },
- retry: false,
- staleTime: 0,
- gcTime: 0,
- };
+ return useQuery(() => agentSessionExternalUrlQueryOptions(sessionId()));
+}
+
+function agentSessionExternalUrlQueryOptions(id: string | undefined) {
+ return queryOptions({
+ queryKey: ['agentSession', 'externalUrl', id ?? ''] as const,
+ queryFn: async () =>
+ await throwOnErr(() => agentHarnessServiceClient.get(id!)),
+ enabled: Boolean(id),
+ // Stop once the url lands or the attempt budget is spent. Failed
+ // fetches count too, so a streak of errors cannot poll forever.
+ refetchInterval: (query) => {
+ if (query.state.data?.external?.url) return false;
+ const attempts =
+ query.state.dataUpdateCount + query.state.errorUpdateCount;
+ if (attempts >= EXTERNAL_URL_POLL_ATTEMPTS) return false;
+ return EXTERNAL_URL_POLL_INTERVAL_MS;
+ },
+ retry: false,
+ staleTime: 0,
+ gcTime: 0,
});
}
const STATUS_POLL_INTERVAL_MS = 5_000;
const MAX_STATUS_POLLS = 120;
-/** Shared session metadata, polling only while the session is starting. */
-export function useAgentSessionQuery(id: Accessor<string>) {
- return useQuery(() => ({
- queryKey: agentSessionKeys.detail(id()).queryKey,
- queryFn: () => throwOnErr(() => agentHarnessServiceClient.get(id())),
+function agentSessionQueryOptions(id: string) {
+ return queryOptions({
+ queryKey: agentSessionKeys.detail(id).queryKey,
+ queryFn: () => throwOnErr(() => agentHarnessServiceClient.get(id)),
staleTime: 0,
retry: false,
refetchInterval: (query) => {
@@ -81,5 +81,10 @@ export function useAgentSessionQuery(id: Accessor<string>) {
return STATUS_POLL_INTERVAL_MS;
return false;
},
- }));
+ });
+}
+
+/** Shared session metadata, polling only while the session is starting. */
+export function useAgentSessionQuery(id: Accessor<string>) {
+ return useQuery(() => agentSessionQueryOptions(id()));
}
diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.ts
index f5fe25b6dd..00d5b9fe9e 100644
--- a/apps/web/src/lib/queries/agents/agents.ts
+++ b/apps/web/src/lib/queries/agents/agents.ts
@@ -54,12 +54,15 @@ export type DeleteAgentParams = {
channelIds: string[];
};
+async function fetchAgents(): Promise<AgentWithHarnessId[]> {
+ return await throwOnErr(() => storageServiceClient.getAgents());
+}
+
export function useAgentsQuery(enabled: Accessor<boolean> = () => true) {
return useQuery(() => ({
queryKey: agentKeys.list.queryKey,
enabled: enabled(),
- queryFn: async (): Promise<AgentWithHarnessId[]> =>
- await throwOnErr(() => storageServiceClient.getAgents()),
+ queryFn: fetchAgents,
}));
}
diff --git a/apps/web/src/lib/queries/ai/projection.ts b/apps/web/src/lib/queries/ai/projection.ts
index 42a9a428ec..33213bde2d 100644
--- a/apps/web/src/lib/queries/ai/projection.ts
+++ b/apps/web/src/lib/queries/ai/projection.ts
@@ -7,10 +7,9 @@ import type { RefreshCadence } from '@service-cognition/generated/schemas/refres
import type { TargetType } from '@service-cognition/generated/schemas/targetType';
import type { UpsertProjectionRequest } from '@service-cognition/generated/schemas/upsertProjectionRequest';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery, useQueryClient } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
import { z } from 'zod';
-import { queryClient } from '../client';
const AI_PROJECTION_UPDATED_MESSAGE_TYPE = 'ai_projection_updated';
@@ -73,6 +72,49 @@ function toOutputSchema(schema: z.ZodType): Record<string, unknown> {
}) as Record<string, unknown>;
}
+/** Builds the upsert request from one options snapshot. Schema conversion can
+ * throw, so callers run this inside the query function (or `refresh`) where
+ * the error surfaces through the query rather than during component setup. */
+function buildProjectionRequest(
+ opts: CreateAIProjectionOptions<z.ZodType>,
+ overrides?: Partial<UpsertProjectionRequest>
+): UpsertProjectionRequest {
+ return {
+ id: opts.id,
+ prompt: opts.prompt,
+ target_type: opts.targetType ?? 'user',
+ refresh_cadence: opts.refreshCadence ?? 'medium',
+ expiry: opts.expiry ?? 'week',
+ ...(opts.model === undefined ? {} : { model: opts.model }),
+ ...(opts.schema === undefined
+ ? {}
+ : { output_schema: toOutputSchema(opts.schema) }),
+ await: opts.awaitGeneration ?? false,
+ ...overrides,
+ };
+}
+
+// Cached past unmount: closes over the caller's plain options snapshot, not
+// the options accessor, so an unmounted caller can be collected.
+function aiProjectionQueryOptions(
+ queryKey: ReturnType<typeof aiProjectionQueryKey>,
+ opts: CreateAIProjectionOptions<z.ZodType>,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey,
+ queryFn: async () =>
+ throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.upsertAiProjection(
+ buildProjectionRequest(opts)
+ )
+ ),
+ enabled,
+ staleTime: PROJECTION_STALE_TIME,
+ });
+}
+
function toProjectionState(
message: ProjectionUpdatedMessage
): ProjectionStateResponse {
@@ -120,37 +162,17 @@ export function createAIProjection<Schema extends z.ZodType>(
) {
const targetType = () => options().targetType ?? 'user';
const queryKey = () => aiProjectionQueryKey(options().id, targetType());
+ // Write through the same client the query observes so tests and hosts that
+ // provide their own QueryClient see refreshes and gateway pushes.
+ const queryClient = useQueryClient();
- const buildRequest = (
- overrides?: Partial<UpsertProjectionRequest>
- ): UpsertProjectionRequest => {
- const opts = options();
- return {
- id: opts.id,
- prompt: opts.prompt,
- target_type: targetType(),
- refresh_cadence: opts.refreshCadence ?? 'medium',
- expiry: opts.expiry ?? 'week',
- ...(opts.model === undefined ? {} : { model: opts.model }),
- ...(opts.schema === undefined
- ? {}
- : { output_schema: toOutputSchema(opts.schema) }),
- await: opts.awaitGeneration ?? false,
- ...overrides,
- };
- };
-
- const query = useQuery(() => ({
- queryKey: queryKey(),
- queryFn: async () =>
- throwOnErr(
- async () =>
- await cognitionApiServiceClient.upsertAiProjection(buildRequest())
- ),
- enabled:
- (options().enabled ?? true) && !!options().id && !!options().prompt,
- staleTime: PROJECTION_STALE_TIME,
- }));
+ const query = useQuery(() =>
+ aiProjectionQueryOptions(
+ queryKey(),
+ options(),
+ (options().enabled ?? true) && !!options().id && !!options().prompt
+ )
+ );
// Materializations finish out-of-band (SQS worker or refresh sweeps); the
// gateway pushes the final state, which we write straight into the cache.
@@ -179,7 +201,7 @@ export function createAIProjection<Schema extends z.ZodType>(
const state = await throwOnErr(
async () =>
await cognitionApiServiceClient.upsertAiProjection(
- buildRequest({ regenerate: true })
+ buildProjectionRequest(options(), { regenerate: true })
)
);
queryClient.setQueryData(key, state);
diff --git a/apps/web/src/lib/queries/auth/codex.ts b/apps/web/src/lib/queries/auth/codex.ts
index 97a76197f2..f4eba17746 100644
--- a/apps/web/src/lib/queries/auth/codex.ts
+++ b/apps/web/src/lib/queries/auth/codex.ts
@@ -5,7 +5,7 @@ import {
type CodexLogin,
codexClient,
} from '@service-auth/codex';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import { authKeys } from './keys';
const invalidateConnection = async () => {
@@ -16,10 +16,11 @@ const invalidateConnection = async () => {
}),
]);
};
-export function useCodexStatusQuery(enabled: () => boolean = () => true) {
- return useQuery(() => ({
+// Cached callbacks close over plain values only; hooks resolve accessors.
+function codexStatusQueryOptions(enabled: boolean) {
+ return queryOptions({
queryKey: authKeys.codexStatus.queryKey,
- enabled: enabled(),
+ enabled,
queryFn: () => throwOnErr(codexClient.status),
placeholderData: {
connected: false,
@@ -27,14 +28,17 @@ export function useCodexStatusQuery(enabled: () => boolean = () => true) {
accountId: null,
environmentId: null,
},
- }));
+ });
}
-export function useCodexLoginQuery(attempt: () => CodexLogin | undefined) {
- return useQuery(() => ({
- queryKey: authKeys.codexLogin(attempt()?.attemptId ?? '').queryKey,
- enabled: !!attempt(),
+export function useCodexStatusQuery(enabled: () => boolean = () => true) {
+ return useQuery(() => codexStatusQueryOptions(enabled()));
+}
+function codexLoginQueryOptions(login: CodexLogin | undefined) {
+ const pollIntervalMs = Math.max(1, login?.pollIntervalSeconds ?? 5) * 1000;
+ return queryOptions({
+ queryKey: authKeys.codexLogin(login?.attemptId ?? '').queryKey,
+ enabled: !!login,
queryFn: async () => {
- const login = attempt();
if (!login) throw new Error('No active Codex login');
const result = await throwOnErr(() => codexClient.poll(login.attemptId));
if (result.status === 'connected') await invalidateConnection();
@@ -44,16 +48,22 @@ export function useCodexLoginQuery(attempt: () => CodexLogin | undefined) {
refetchInterval: (query) =>
query.state.data && query.state.data.status !== 'pending'
? false
- : Math.max(1, attempt()?.pollIntervalSeconds ?? 5) * 1000,
+ : pollIntervalMs,
refetchIntervalInBackground: true,
- }));
+ });
}
-export function useCodexEnvironmentsQuery(enabled: () => boolean) {
- return useQuery(() => ({
+export function useCodexLoginQuery(attempt: () => CodexLogin | undefined) {
+ return useQuery(() => codexLoginQueryOptions(attempt()));
+}
+function codexEnvironmentsQueryOptions(enabled: boolean) {
+ return queryOptions({
queryKey: authKeys.codexEnvironments.queryKey,
- enabled: enabled(),
+ enabled,
queryFn: () => throwOnErr(codexClient.environments),
- }));
+ });
+}
+export function useCodexEnvironmentsQuery(enabled: () => boolean) {
+ return useQuery(() => codexEnvironmentsQueryOptions(enabled()));
}
export function useBeginCodexLogin() {
return useMutation(() => ({
diff --git a/apps/web/src/lib/queries/auth/cursor-api-key.ts b/apps/web/src/lib/queries/auth/cursor-api-key.ts
index 9783dac6bb..869c73db41 100644
--- a/apps/web/src/lib/queries/auth/cursor-api-key.ts
+++ b/apps/web/src/lib/queries/auth/cursor-api-key.ts
@@ -6,6 +6,14 @@ import { useMutation, useQuery } from '@tanstack/solid-query';
import { authKeys } from './keys';
+function fetchCursorApiKeyStatus() {
+ return throwOnErr(() => authServiceClient.getCursorApiKeyStatus());
+}
+
+function fetchCursorModels() {
+ return throwOnErr(() => authServiceClient.listCursorModels());
+}
+
/**
* What the query reads as before its answer arrives. Placeholder rather than
* pending, so reading `data` never suspends the surface asking — the message
@@ -32,8 +40,7 @@ export function useCursorApiKeyStatusQuery(
return useQuery(() => ({
queryKey: authKeys.cursorApiKeyStatus.queryKey,
enabled: enabled(),
- queryFn: async () =>
- throwOnErr(async () => await authServiceClient.getCursorApiKeyStatus()),
+ queryFn: fetchCursorApiKeyStatus,
placeholderData: NOT_CONNECTED,
}));
}
@@ -86,8 +93,7 @@ export function useDisconnectCursorApiKey() {
export function useCursorModelsQuery(enabled: () => boolean) {
return useQuery(() => ({
queryKey: authKeys.cursorModels.queryKey,
- queryFn: async () =>
- throwOnErr(async () => await authServiceClient.listCursorModels()),
+ queryFn: fetchCursorModels,
enabled: enabled(),
staleTime: 5 * 60 * 1000,
}));
diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.ts
index 84098905c3..5760d502a5 100644
--- a/apps/web/src/lib/queries/auth/user-info.ts
+++ b/apps/web/src/lib/queries/auth/user-info.ts
@@ -3,7 +3,7 @@ import { enableUserInfoQuery } from '@core/context/user-info-gate';
import { hasLoginCookie } from '@core/util/cookies';
import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import { resetTeamCalendarSession } from '../calendar/team-cache';
import { queryClient, queryPersistence } from '../client';
import { resetGraphqlSoupDoneSession } from '../soup/graphql/done-session';
@@ -23,32 +23,38 @@ type UseUserInfoQueryOptions = {
enabled?: boolean | (() => boolean);
};
+function fetchLegacyUserPermissions() {
+ return throwOnErr(() => authServiceClient.getLegacyUserPermissions());
+}
+
+// Cached callbacks stay at module scope so they never retain the caller.
+function userInfoQueryOptions(enabled: boolean) {
+ return queryOptions({
+ queryKey: authKeys.userInfo.queryKey,
+ queryFn: fetchLegacyUserPermissions,
+ throwOnError: false,
+ staleTime: USER_INFO_STALE_TIME,
+ // Signed-out screens also observe this query. Retrying their cached 401
+ // on mount resets auth to loading, unmounts them, and repeats forever.
+ // Successful login explicitly invalidates the query to refresh identity.
+ retryOnMount: false,
+ // Never pause on navigator.onLine — it reports false during native cold
+ // launches (e.g. woken by a notification tap) while the network is fine,
+ // and a paused auth check renders as "unauthenticated" at the base path.
+ networkMode: 'always',
+ enabled,
+ });
+}
+
/** Query for the current user's info and permissions. */
export function useUserInfoQuery(options?: UseUserInfoQueryOptions) {
- return useQuery(() => {
- const enabled =
+ return useQuery(() =>
+ userInfoQueryOptions(
typeof options?.enabled === 'function'
? options.enabled()
- : (options?.enabled ?? true);
- return {
- queryKey: authKeys.userInfo.queryKey,
- queryFn: async () =>
- await throwOnErr(
- async () => await authServiceClient.getLegacyUserPermissions()
- ),
- throwOnError: false,
- staleTime: USER_INFO_STALE_TIME,
- // Signed-out screens also observe this query. Retrying their cached 401
- // on mount resets auth to loading, unmounts them, and repeats forever.
- // Successful login explicitly invalidates the query to refresh identity.
- retryOnMount: false,
- // Never pause on navigator.onLine — it reports false during native cold
- // launches (e.g. woken by a notification tap) while the network is fine,
- // and a paused auth check renders as "unauthenticated" at the base path.
- networkMode: 'always',
- enabled,
- };
- });
+ : (options?.enabled ?? true)
+ )
+ );
}
/** Invalidate the user info query to trigger a refetch. */
@@ -94,10 +100,7 @@ export async function prefetchUserInfo() {
async () =>
await queryClient.fetchQuery({
queryKey: authKeys.userInfo.queryKey,
- queryFn: async () =>
- await throwOnErr(
- async () => await authServiceClient.getLegacyUserPermissions()
- ),
+ queryFn: fetchLegacyUserPermissions,
networkMode: 'always',
// Even a fresh in-memory logout stub is not the new login's identity.
staleTime: 0,
@@ -109,10 +112,7 @@ export async function prefetchUserInfo() {
export async function fetchUserInfo() {
return queryClient.fetchQuery({
queryKey: authKeys.userInfo.queryKey,
- queryFn: async () =>
- await throwOnErr(
- async () => await authServiceClient.getLegacyUserPermissions()
- ),
+ queryFn: fetchLegacyUserPermissions,
networkMode: 'always',
});
}
diff --git a/apps/web/src/lib/queries/auth/user-name-self.ts b/apps/web/src/lib/queries/auth/user-name-self.ts
index 42b4a5a7fe..5db564b0a3 100644
--- a/apps/web/src/lib/queries/auth/user-name-self.ts
+++ b/apps/web/src/lib/queries/auth/user-name-self.ts
@@ -2,7 +2,7 @@ import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { authServiceClient } from '@service-auth/client';
import type { UserName } from '@service-auth/generated/schemas/userName';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { authKeys } from './keys';
@@ -15,13 +15,20 @@ const OWN_USER_NAME_STALE_TIME = 15_000;
* useUserNamesQuery (other users, batched by macro id).
*/
export function useOwnUserNameQuery() {
- return useQuery(() => ({
+ return useQuery(ownUserNameQueryOptions);
+}
+
+function fetchOwnUserName() {
+ return throwOnErr(() => authServiceClient.getUserName());
+}
+
+function ownUserNameQueryOptions() {
+ return queryOptions({
queryKey: authKeys.userNameSelf.queryKey,
- queryFn: async () =>
- throwOnErr(async () => await authServiceClient.getUserName()),
+ queryFn: fetchOwnUserName,
staleTime: OWN_USER_NAME_STALE_TIME,
- refetchOnWindowFocus: 'always' as const,
- }));
+ refetchOnWindowFocus: 'always',
+ });
}
/**
diff --git a/apps/web/src/lib/queries/blame.ts b/apps/web/src/lib/queries/blame.ts
index 3a51aaae90..184106e33e 100644
--- a/apps/web/src/lib/queries/blame.ts
+++ b/apps/web/src/lib/queries/blame.ts
@@ -1,23 +1,26 @@
import { enableGitBlame, isFeatureEnabled } from '@core/constant/featureFlags';
import { syncServiceClient } from '@service-sync/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
+
+async function fetchNodeBlame(documentId: string, nodeId: string) {
+ const res = await syncServiceClient.getNodeBlame({ documentId, nodeId });
+ if (!res.isOk()) throw new Error('blame_not_found');
+ return res.value;
+}
+
+function nodeBlameQueryOptions(documentId: string, nodeId: string | null) {
+ return queryOptions({
+ queryKey: ['blame', documentId, nodeId],
+ queryFn: () => fetchNodeBlame(documentId, nodeId!),
+ enabled: isFeatureEnabled(enableGitBlame) && nodeId !== null,
+ staleTime: Infinity,
+ retry: false,
+ });
+}
export function useNodeBlameQuery(
documentId: string,
nodeId: () => string | null
) {
- return useQuery(() => ({
- queryKey: ['blame', documentId, nodeId()],
- queryFn: async () => {
- const res = await syncServiceClient.getNodeBlame({
- documentId,
- nodeId: nodeId()!,
- });
- if (!res.isOk()) throw new Error('blame_not_found');
- return res.value;
- },
- enabled: isFeatureEnabled(enableGitBlame) && nodeId() !== null,
- staleTime: Infinity,
- retry: false,
- }));
+ return useQuery(() => nodeBlameQueryOptions(documentId, nodeId()));
}
diff --git a/apps/web/src/lib/queries/bots/bots.ts b/apps/web/src/lib/queries/bots/bots.ts
index 56a9505f6e..f0356db453 100644
--- a/apps/web/src/lib/queries/bots/bots.ts
+++ b/apps/web/src/lib/queries/bots/bots.ts
@@ -43,12 +43,16 @@ export function useBotsQuery(enabled: () => boolean = () => true) {
return useQuery(() => ({ ...botsQueryOptions(), enabled: enabled() }));
}
-export function useBotQuery(botId: () => string) {
- return useQuery(() => ({
- queryKey: botKeys.detail(botId()).queryKey,
+function botQueryOptions(botId: string) {
+ return queryOptions({
+ queryKey: botKeys.detail(botId).queryKey,
queryFn: async (): Promise<Bot> =>
- await throwOnErr(() => storageServiceClient.getBot({ bot_id: botId() })),
- }));
+ await throwOnErr(() => storageServiceClient.getBot({ bot_id: botId })),
+ });
+}
+
+export function useBotQuery(botId: () => string) {
+ return useQuery(() => botQueryOptions(botId()));
}
export function invalidateBots() {
@@ -157,14 +161,18 @@ export function useCreateBotTokenMutation() {
}));
}
-export function useBotChannelsQuery(botId: () => string) {
- return useQuery(() => ({
- queryKey: botKeys.channels(botId()).queryKey,
+function botChannelsQueryOptions(botId: string) {
+ return queryOptions({
+ queryKey: botKeys.channels(botId).queryKey,
queryFn: async () =>
await throwOnErr(() =>
- storageServiceClient.getBotChannels({ bot_id: botId() })
+ storageServiceClient.getBotChannels({ bot_id: botId })
),
- }));
+ });
+}
+
+export function useBotChannelsQuery(botId: () => string) {
+ return useQuery(() => botChannelsQueryOptions(botId()));
}
export function invalidateBotChannels(botId: string) {
diff --git a/apps/web/src/lib/queries/calendar/calendars.ts b/apps/web/src/lib/queries/calendar/calendars.ts
index a88cc45030..a1430359c2 100644
--- a/apps/web/src/lib/queries/calendar/calendars.ts
+++ b/apps/web/src/lib/queries/calendar/calendars.ts
@@ -5,7 +5,11 @@ import type { VisibleCalendar } from '@service-calendar/generated/schemas/visibl
import { emailClient } from '@service-email/client';
import { CalendarsDocument } from '@service-storage/graphql/generated/graphql';
import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
-import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import {
+ keepPreviousData,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/solid-query';
import { type Accessor, createEffect, onCleanup } from 'solid-js';
import { useGraphqlCalendarHost } from './graphql/flag';
import { mapVisibleCalendar } from './graphql/map';
@@ -50,26 +54,36 @@ export function useVisibleCalendarsQuery(
| typeof calendarKeys.visibleCalendars._ctx.graphql.queryKey
>(() => {
const host = cacheHost();
- if (host) {
- return {
- queryKey: calendarKeys.visibleCalendars._ctx.graphql.queryKey,
- queryFn: () => readCalendarList(host),
- staleTime: Infinity,
- networkMode: 'offlineFirst' as const,
- enabled: options?.().enabled !== false,
- placeholderData: (previous: VisibleCalendar[] | undefined) => previous,
- };
- }
- return {
- queryKey: calendarKeys.visibleCalendars.queryKey,
- queryFn: listCalendars,
- staleTime: CALENDAR_LIST_STALE_TIME,
- enabled: options?.().enabled !== false,
- placeholderData: (previous: VisibleCalendar[] | undefined) => previous,
- };
+ const enabled = options?.().enabled !== false;
+ return host
+ ? cachedVisibleCalendarsQueryOptions(host, enabled)
+ : visibleCalendarsQueryOptions(enabled);
});
}
+// Cached options outlive the hook. The host is the app-level cache service,
+// not component state, so the factory may close over it.
+function cachedVisibleCalendarsQueryOptions(host: CacheHost, enabled: boolean) {
+ return {
+ queryKey: calendarKeys.visibleCalendars._ctx.graphql.queryKey,
+ queryFn: () => readCalendarList(host),
+ staleTime: Infinity,
+ networkMode: 'offlineFirst' as const,
+ enabled,
+ placeholderData: keepPreviousData,
+ };
+}
+
+function visibleCalendarsQueryOptions(enabled: boolean) {
+ return {
+ queryKey: calendarKeys.visibleCalendars.queryKey,
+ queryFn: listCalendars,
+ staleTime: CALENDAR_LIST_STALE_TIME,
+ enabled,
+ placeholderData: keepPreviousData,
+ };
+}
+
async function listCalendars() {
return (await throwOnErr(() => emailClient.listCalendars())).calendars;
}
diff --git a/apps/web/src/lib/queries/calendar/mention-preview.ts b/apps/web/src/lib/queries/calendar/mention-preview.ts
index e425ba71aa..94bdb0473e 100644
--- a/apps/web/src/lib/queries/calendar/mention-preview.ts
+++ b/apps/web/src/lib/queries/calendar/mention-preview.ts
@@ -4,7 +4,7 @@ import type { PreviewItem } from '@queries/preview/types';
import { storageServiceClient } from '@service-storage/client';
import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';
import type { CalendarMentionPreviewRequestItem } from '@service-storage/generated/schemas/calendarMentionPreviewRequestItem';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { calendarKeys } from './keys';
@@ -94,20 +94,31 @@ export function useCalendarMentionPreviewQuery(
) {
return useQuery(() => {
const target = input();
- return {
- queryKey: calendarKeys.mentionPreview(
- target?.eventId ?? '',
- target?.occurrenceKey
- ).queryKey,
- queryFn: () => {
- if (!target) {
- throw new Error('Calendar mention preview target is unavailable');
- }
- return fetchPreview(target.eventId, target.occurrenceKey);
- },
- enabled: target !== undefined && options?.().enabled !== false,
- staleTime: MENTION_PREVIEW_STALE_TIME,
- };
+ return calendarMentionPreviewQueryOptions(
+ target?.eventId,
+ target?.occurrenceKey,
+ options?.().enabled !== false
+ );
+ });
+}
+
+// Closes over the target's plain fields only, never the caller's accessors.
+function calendarMentionPreviewQueryOptions(
+ eventId: string | undefined,
+ occurrenceKey: string | undefined,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: calendarKeys.mentionPreview(eventId ?? '', occurrenceKey)
+ .queryKey,
+ queryFn: () => {
+ if (eventId === undefined) {
+ throw new Error('Calendar mention preview target is unavailable');
+ }
+ return fetchPreview(eventId, occurrenceKey);
+ },
+ enabled: eventId !== undefined && enabled,
+ staleTime: MENTION_PREVIEW_STALE_TIME,
});
}
@@ -115,23 +126,24 @@ export function useCalendarMentionPreviewQuery(
export function useCalendarSearchPreviewsQuery(
inputs: Accessor<CalendarMentionPreviewRequestItem[]>
) {
- return useQuery(() => {
- const items = inputs();
- return {
- queryKey: calendarKeys.searchPreviews(items).queryKey,
- queryFn: async () => {
- const result = await storageServiceClient.getBatchCalendarEventPreviews(
- {
- items,
- }
- );
- if (result.isErr()) {
- throw new Error('Failed to fetch calendar search previews');
- }
- return result.value.items;
- },
- enabled: items.length > 0,
- staleTime: MENTION_PREVIEW_STALE_TIME,
- };
+ return useQuery(() => calendarSearchPreviewsQueryOptions(inputs()));
+}
+
+function calendarSearchPreviewsQueryOptions(
+ items: CalendarMentionPreviewRequestItem[]
+) {
+ return queryOptions({
+ queryKey: calendarKeys.searchPreviews(items).queryKey,
+ queryFn: async () => {
+ const result = await storageServiceClient.getBatchCalendarEventPreviews({
+ items,
+ });
+ if (result.isErr()) {
+ throw new Error('Failed to fetch calendar search previews');
+ }
+ return result.value.items;
+ },
+ enabled: items.length > 0,
+ staleTime: MENTION_PREVIEW_STALE_TIME,
});
}
diff --git a/apps/web/src/lib/queries/calendar/occurrences.ts b/apps/web/src/lib/queries/calendar/occurrences.ts
index 5d68ac2b5f..7e1427c551 100644
--- a/apps/web/src/lib/queries/calendar/occurrences.ts
+++ b/apps/web/src/lib/queries/calendar/occurrences.ts
@@ -1,11 +1,12 @@
import { throwOnErr } from '@core/util/result';
+import type { CacheHost } from '@graphql-cache/index';
import { queryClient } from '@queries/client';
import { subscribeToVisibleCacheChanges } from '@queries/subscribe-to-visible-cache-changes';
import { storageServiceClient } from '@service-storage/client';
import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
import type { CalendarOccurrenceResponse } from '@service-storage/generated/schemas/calendarOccurrenceResponse';
import { CalendarSyncStatus } from '@service-storage/generated/schemas/calendarSyncStatus';
-import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import { queryOptions, useQuery, useQueryClient } from '@tanstack/solid-query';
import { type Accessor, createEffect, onCleanup } from 'solid-js';
import {
markCalendarCacheUnsupported,
@@ -109,6 +110,81 @@ export async function fetchCalendarOccurrences(
};
}
+// Cached callbacks close over the resolved host, range and flags only.
+function calendarOccurrencesQueryOptions(
+ host: CacheHost | undefined,
+ userId: string | undefined,
+ range: CalendarOccurrenceQueryRange | undefined,
+ enabled: boolean,
+ pollWhileSyncing: boolean,
+ refetchOnWindowFocus: boolean
+) {
+ const keys = calendarKeys.occurrences(userId ?? '', range);
+ // Even the otherwise infinitely fresh GraphQL query must run once after
+ // being seeded. A successful read restores its normal freshness policy.
+ const staleTime = (query: { state: { dataUpdatedAt: number } }) =>
+ query.state.dataUpdatedAt === 0 ? 0 : host ? Infinity : CALENDAR_STALE_TIME;
+
+ if (host) {
+ return queryOptions<
+ CalendarOccurrencesData,
+ Error,
+ CalendarOccurrencesData,
+ CalendarOccurrencesQueryKey
+ >({
+ queryKey: keys._ctx.graphql.queryKey,
+ queryFn: async ({ signal }: { signal: AbortSignal }) => {
+ if (!range) {
+ throw new Error('Calendar occurrence range is unavailable');
+ }
+ const read = await readCalendarRange(host, range, { signal });
+ if (read.kind === 'range') return read.data;
+ if (read.kind === 'unsupported') markCalendarCacheUnsupported(host);
+ return fetchCalendarOccurrences(range, signal);
+ },
+ enabled,
+ staleTime,
+ // Covered viewports never touch the network, so offline reads run.
+ networkMode: 'offlineFirst' as const,
+ refetchOnWindowFocus: false,
+ // Read from REST while the cache was starting: poll like the REST
+ // path until the provider sync finishes.
+ refetchInterval: (query: {
+ state: { data: CalendarOccurrencesData | undefined };
+ }) =>
+ pollWhileSyncing &&
+ !calendarCacheAnswered(host) &&
+ query.state.data?.syncStatus === CalendarSyncStatus.syncing
+ ? CALENDAR_SYNC_POLL_INTERVAL
+ : false,
+ });
+ }
+
+ return queryOptions<
+ CalendarOccurrencesData,
+ Error,
+ CalendarOccurrencesData,
+ CalendarOccurrencesQueryKey
+ >({
+ queryKey: keys.queryKey,
+ queryFn: ({ signal }) => {
+ if (!range) {
+ throw new Error('Calendar occurrence range is unavailable');
+ }
+
+ return fetchCalendarOccurrences(range, signal);
+ },
+ enabled,
+ staleTime,
+ refetchOnWindowFocus,
+ refetchInterval: (query) =>
+ pollWhileSyncing &&
+ query.state.data?.syncStatus === CalendarSyncStatus.syncing
+ ? CALENDAR_SYNC_POLL_INTERVAL
+ : false,
+ });
+}
+
/** Reuses only the current user's date range when the transport changes. */
export function useCalendarOccurrencesQuery(
input: Accessor<CalendarOccurrencesQueryInput>,
@@ -140,8 +216,7 @@ export function useCalendarOccurrencesQuery(
CalendarOccurrencesQueryKey
>(() => {
const { userId, range } = input();
- const enabled =
- Boolean(userId) && range !== undefined && options?.().enabled !== false;
+ const opts = options?.();
const host = cacheHost();
const keys = calendarKeys.occurrences(userId ?? '', range);
// Seed the new transport's cache, rather than an observer-only placeholder,
@@ -155,64 +230,15 @@ export function useCalendarOccurrencesQuery(
activeQueryClient.setQueryData(queryKey, previous, { updatedAt: 0 });
}
}
- // Even the otherwise infinitely fresh GraphQL query must run once after
- // being seeded. A successful read restores its normal freshness policy.
- const staleTime = (query: { state: { dataUpdatedAt: number } }) =>
- query.state.dataUpdatedAt === 0
- ? 0
- : host
- ? Infinity
- : CALENDAR_STALE_TIME;
-
- if (host) {
- return {
- queryKey: keys._ctx.graphql.queryKey,
- queryFn: async ({ signal }: { signal: AbortSignal }) => {
- if (!range) {
- throw new Error('Calendar occurrence range is unavailable');
- }
- const read = await readCalendarRange(host, range, { signal });
- if (read.kind === 'range') return read.data;
- if (read.kind === 'unsupported') markCalendarCacheUnsupported(host);
- return fetchCalendarOccurrences(range, signal);
- },
- enabled,
- staleTime,
- // Covered viewports never touch the network, so offline reads run.
- networkMode: 'offlineFirst' as const,
- refetchOnWindowFocus: false,
- // Read from REST while the cache was starting: poll like the REST
- // path until the provider sync finishes.
- refetchInterval: (query: {
- state: { data: CalendarOccurrencesData | undefined };
- }) =>
- options?.().pollWhileSyncing !== false &&
- !calendarCacheAnswered(host) &&
- query.state.data?.syncStatus === CalendarSyncStatus.syncing
- ? CALENDAR_SYNC_POLL_INTERVAL
- : false,
- };
- }
- return {
- queryKey: keys.queryKey,
- queryFn: ({ signal }) => {
- if (!range) {
- throw new Error('Calendar occurrence range is unavailable');
- }
-
- return fetchCalendarOccurrences(range, signal);
- },
- enabled:
- Boolean(userId) && range !== undefined && options?.().enabled !== false,
- staleTime,
- refetchOnWindowFocus: options?.().refetchOnWindowFocus ?? true,
- refetchInterval: (query) =>
- options?.().pollWhileSyncing !== false &&
- query.state.data?.syncStatus === CalendarSyncStatus.syncing
- ? CALENDAR_SYNC_POLL_INTERVAL
- : false,
- };
+ return calendarOccurrencesQueryOptions(
+ host,
+ userId,
+ range,
+ Boolean(userId) && range !== undefined && opts?.enabled !== false,
+ opts?.pollWhileSyncing !== false,
+ opts?.refetchOnWindowFocus ?? true
+ );
});
}
diff --git a/apps/web/src/lib/queries/calendar/team-ooo.ts b/apps/web/src/lib/queries/calendar/team-ooo.ts
index b9c7e25db7..a508b60a3e 100644
--- a/apps/web/src/lib/queries/calendar/team-ooo.ts
+++ b/apps/web/src/lib/queries/calendar/team-ooo.ts
@@ -2,7 +2,7 @@ import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teamOutOfOfficeItem';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { type CalendarOccurrenceQueryRange, calendarKeys } from './keys';
import { useCalendarTeamIdentityQuery } from './team';
@@ -34,6 +34,34 @@ export async function fetchTeamOutOfOffice(
return response.items;
}
+// Cached callbacks close over the resolved range and flags only.
+function teamOutOfOfficeQueryOptions(
+ userId: string | undefined,
+ range: CalendarOccurrenceQueryRange | undefined,
+ teamId: string | undefined,
+ enabled: boolean,
+ refetchOnWindowFocus: boolean
+) {
+ return queryOptions({
+ queryKey: calendarKeys.teamOutOfOffice(userId ?? '', range, teamId)
+ .queryKey,
+ queryFn: ({ signal }) => {
+ if (!range) {
+ throw new Error('Team out-of-office range is unavailable');
+ }
+
+ return fetchTeamOutOfOffice(range, signal);
+ },
+ enabled:
+ Boolean(userId) && Boolean(teamId) && range !== undefined && enabled,
+ staleTime: 0,
+ gcTime: 0,
+ refetchInterval: 30_000,
+ refetchOnReconnect: 'always',
+ refetchOnWindowFocus,
+ });
+}
+
export function useTeamOutOfOfficeQuery(
input: Accessor<TeamOutOfOfficeQueryInput>,
options?: Accessor<TeamOutOfOfficeQueryOptions>
@@ -44,33 +72,20 @@ export function useTeamOutOfOfficeQuery(
);
return useQuery(() => {
const { userId, range } = input();
+ const opts = options?.();
const team =
identity.isSuccess && !identity.isPaused ? identity.data : undefined;
const teamId = team?.members.some((member) => member.user_id === userId)
? team.team.id
: undefined;
- return {
- queryKey: calendarKeys.teamOutOfOffice(userId ?? '', range, teamId)
- .queryKey,
- queryFn: ({ signal }: { signal?: AbortSignal }) => {
- if (!range) {
- throw new Error('Team out-of-office range is unavailable');
- }
-
- return fetchTeamOutOfOffice(range, signal);
- },
- enabled:
- Boolean(userId) &&
- Boolean(teamId) &&
- range !== undefined &&
- options?.().enabled !== false,
- staleTime: 0,
- gcTime: 0,
- refetchInterval: 30_000,
- refetchOnReconnect: 'always',
- refetchOnWindowFocus: options?.().refetchOnWindowFocus ?? true,
- };
+ return teamOutOfOfficeQueryOptions(
+ userId,
+ range,
+ teamId,
+ opts?.enabled !== false,
+ opts?.refetchOnWindowFocus ?? true
+ );
});
}
diff --git a/apps/web/src/lib/queries/call/call.ts b/apps/web/src/lib/queries/call/call.ts
index d036d1a01e..778c534eb3 100644
--- a/apps/web/src/lib/queries/call/call.ts
+++ b/apps/web/src/lib/queries/call/call.ts
@@ -7,17 +7,21 @@ import type { ActiveCallSummary } from '@service-storage/generated/schemas/activ
import type { CallActiveResponse } from '@service-storage/generated/schemas/callActiveResponse';
import type { SharePermissionV2 } from '@service-storage/generated/schemas/sharePermissionV2';
import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { callKeys } from './keys';
-export function useActiveCallQuery(channelId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: callKeys.active(channelId()).queryKey,
- queryFn: () => fetchActiveCall(channelId()),
+function activeCallQueryOptions(channelId: string) {
+ return queryOptions({
+ queryKey: callKeys.active(channelId).queryKey,
+ queryFn: () => fetchActiveCall(channelId),
placeholderData: null,
refetchInterval: 15_000,
- }));
+ });
+}
+
+export function useActiveCallQuery(channelId: Accessor<string>) {
+ return useQuery(() => activeCallQueryOptions(channelId()));
}
/** Fresh lookups keep recovery from re-creating a call that already ended. */
@@ -36,14 +40,21 @@ export function requestCallToken(channelId: string) {
* call_started/call_ended handlers keep it live.
*/
export function useActiveCallsQuery() {
- return useQuery(() => ({
+ return useQuery(activeCallsQueryOptions);
+}
+
+function fetchActiveCalls() {
+ return throwOnErr(() => callServiceClient.getActiveCalls());
+}
+
+function activeCallsQueryOptions() {
+ return queryOptions({
queryKey: callKeys.allActive.queryKey,
- queryFn: async () =>
- await throwOnErr(() => callServiceClient.getActiveCalls()),
+ queryFn: fetchActiveCalls,
placeholderData: [] as ActiveCallSummary[],
refetchInterval: 30_000,
enabled: ENABLE_CALLS,
- }));
+ });
}
export function setActiveCallStartedCache(call: CallActiveResponse) {
@@ -147,17 +158,21 @@ export function useLeaveCallMutation() {
}));
}
-export function useCallRecordQuery(callId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: callKeys.record(callId()).queryKey,
+function callRecordQueryOptions(callId: string) {
+ return queryOptions({
+ queryKey: callKeys.record(callId).queryKey,
queryFn: async () =>
- await throwOnErr(() => callServiceClient.getCallRecord(callId())),
+ await throwOnErr(() => callServiceClient.getCallRecord(callId)),
// The call block's load() primes this cache; a stale time keeps that
// primed record from triggering an immediate duplicate fetch on mount.
// Mutations still invalidate, so sharing edits stay reactive.
staleTime: 60_000,
- enabled: callId().length > 0,
- }));
+ enabled: callId.length > 0,
+ });
+}
+
+export function useCallRecordQuery(callId: Accessor<string>) {
+ return useQuery(() => callRecordQueryOptions(callId()));
}
export function fetchCallRecord(
diff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.ts b/apps/web/src/lib/queries/channel-labels/channel-labels.ts
index 1f0f56aab2..57a229e714 100644
--- a/apps/web/src/lib/queries/channel-labels/channel-labels.ts
+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.ts
@@ -6,7 +6,7 @@ import { storageServiceClient } from '@service-storage/client';
import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';
import type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { withCallbacks } from '../utils';
@@ -14,19 +14,22 @@ import { channelLabelKeys } from './keys';
export type { ChannelLabel };
-/** Shared labels for team members; account-private labels otherwise. */
-export function useChannelLabelsQuery() {
- const channelTagsFlag = useFeatureFlag(enableChannelTags);
- return useQuery(() => ({
+function channelLabelsQueryOptions(enabled: boolean) {
+ return queryOptions({
queryKey: channelLabelKeys.list.queryKey,
- enabled: channelTagsFlag().enabled,
- queryFn: async () =>
- await throwOnErr(() => storageServiceClient.channelLabels.list()),
+ enabled,
+ queryFn: () => throwOnErr(() => storageServiceClient.channelLabels.list()),
staleTime: 30_000,
refetchInterval: (query) =>
query.state.data?.labels.some((label) => label.rule) ? 30_000 : false,
retry: false,
- }));
+ });
+}
+
+/** Shared labels for team members; account-private labels otherwise. */
+export function useChannelLabelsQuery() {
+ const channelTagsFlag = useFeatureFlag(enableChannelTags);
+ return useQuery(() => channelLabelsQueryOptions(channelTagsFlag().enabled));
}
/** Non-suspending view of labels, undefined until successfully loaded. */
@@ -57,27 +60,33 @@ async function cancelLabelFetch() {
await queryClient.cancelQueries({ queryKey: channelLabelKeys.list.queryKey });
}
+function smartTagPreviewQueryOptions(contains: string, enabled: boolean) {
+ return queryOptions({
+ queryKey: channelLabelKeys.preview(contains).queryKey,
+ enabled,
+ queryFn: ({ signal }) =>
+ throwOnErr(() =>
+ storageServiceClient.channelLabels.preview(
+ { attribute: 'name', contains },
+ signal
+ )
+ ),
+ staleTime: 0,
+ retry: false,
+ });
+}
+
export function useSmartTagPreviewQuery(pattern: Accessor<string>) {
const channelTagsFlag = useFeatureFlag(enableChannelTags);
const debouncedPattern = debouncedDependent(pattern, 150);
return useQuery(() => {
const contains = pattern();
- return {
- queryKey: channelLabelKeys.preview(contains).queryKey,
- enabled:
- channelTagsFlag().enabled &&
+ return smartTagPreviewQueryOptions(
+ contains,
+ channelTagsFlag().enabled &&
contains.length > 0 &&
- contains === debouncedPattern(),
- queryFn: async ({ signal }) =>
- await throwOnErr(() =>
- storageServiceClient.channelLabels.preview(
- { attribute: 'name', contains },
- signal
- )
- ),
- staleTime: 0,
- retry: false,
- };
+ contains === debouncedPattern()
+ );
});
}
diff --git a/apps/web/src/lib/queries/channel/activity.ts b/apps/web/src/lib/queries/channel/activity.ts
index 92ec36cc93..3effe0e7fb 100644
--- a/apps/web/src/lib/queries/channel/activity.ts
+++ b/apps/web/src/lib/queries/channel/activity.ts
@@ -8,10 +8,14 @@ import { recordChannelActivity } from '@service-storage/graphql-channel-activity
import { useMutation, useQuery } from '@tanstack/solid-query';
import { channelKeys } from './keys';
+function fetchChannelsActivity() {
+ return throwOnErr(storageServiceClient.getActivity);
+}
+
export function useChannelsActivityQuery() {
return useQuery(() => ({
queryKey: channelKeys.activity.queryKey,
- queryFn: async () => await throwOnErr(storageServiceClient.getActivity),
+ queryFn: fetchChannelsActivity,
}));
}
diff --git a/apps/web/src/lib/queries/channel/channel-bots.ts b/apps/web/src/lib/queries/channel/channel-bots.ts
index f29df65165..21131d6a6d 100644
--- a/apps/web/src/lib/queries/channel/channel-bots.ts
+++ b/apps/web/src/lib/queries/channel/channel-bots.ts
@@ -4,7 +4,7 @@ import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { Bot } from '@service-storage/generated/schemas/bot';
import type { CreateChannelScopedBotRequest } from '@service-storage/generated/schemas/createChannelScopedBotRequest';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import { channelKeys } from './keys';
type AddBotToChannelParams = {
@@ -28,17 +28,19 @@ type CreateChannelScopedBotParams = CreateChannelScopedBotRequest & {
has_agent?: boolean;
};
-export function useChannelBotsQuery(channelId: () => string) {
- return useQuery(() => ({
- queryKey: channelKeys.channelBots(channelId()).queryKey,
- enabled: !!channelId(),
- queryFn: async (): Promise<Bot[]> =>
- await throwOnErr(() =>
- storageServiceClient.getChannelBots({
- channel_id: channelId(),
- })
+function channelBotsQueryOptions(channelId: string) {
+ return queryOptions({
+ queryKey: channelKeys.channelBots(channelId).queryKey,
+ enabled: !!channelId,
+ queryFn: (): Promise<Bot[]> =>
+ throwOnErr(() =>
+ storageServiceClient.getChannelBots({ channel_id: channelId })
),
- }));
+ });
+}
+
+export function useChannelBotsQuery(channelId: () => string) {
+ return useQuery(() => channelBotsQueryOptions(channelId()));
}
function invalidateChannelBots(channelId: string) {
diff --git a/apps/web/src/lib/queries/channel/channels.ts b/apps/web/src/lib/queries/channel/channels.ts
index d2b8903936..2b2c903e02 100644
--- a/apps/web/src/lib/queries/channel/channels.ts
+++ b/apps/web/src/lib/queries/channel/channels.ts
@@ -13,7 +13,7 @@ import { ChannelType } from '@service-storage/generated/schemas/channelType';
import type { CreateChannelRequest } from '@service-storage/generated/schemas/createChannelRequest';
import type { CreateChannelResponse } from '@service-storage/generated/schemas/createChannelResponse';
import type { PatchChannelRequest } from '@service-storage/generated/schemas/patchChannelRequest';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { invalidateChannelParticipants } from './channel-participants';
import {
@@ -45,11 +45,28 @@ export async function fetchAllChannels(
return channels;
}
+const listChannelsQueryOptions = queryOptions({
+ queryKey: channelKeys.listChannels.queryKey,
+ queryFn: ({ signal }) => fetchAllChannels(signal),
+});
+
export function useListChannelsQuery() {
- return useQuery(() => ({
- queryKey: channelKeys.listChannels.queryKey,
- queryFn: ({ signal }) => fetchAllChannels(signal),
- }));
+ return useQuery(() => listChannelsQueryOptions);
+}
+
+// The host is an app-level cache service, not component state; the key
+// already namespaces on its client id.
+function cachedGraphqlChannelsQueryOptions(cacheHost: CacheHost | undefined) {
+ return queryOptions({
+ queryKey: channelKeys.quickAccessGraphql(cacheHost?.clientId ?? 'disabled')
+ .queryKey,
+ queryFn: async (): Promise<CachedGraphqlChannel[]> => {
+ if (!cacheHost) return [];
+ return await readCachedGraphqlChannels(cacheHost);
+ },
+ enabled: cacheHost !== undefined,
+ staleTime: Infinity,
+ });
}
/** Reads the recent Quick Access channel list from the normalized GraphQL cache. */
@@ -58,18 +75,7 @@ export function useCachedGraphqlChannelsQuery(
) {
return useQuery(() => {
const host = cacheHost();
- const enabledCacheHost = host?.disabled ? undefined : host;
- return {
- queryKey: channelKeys.quickAccessGraphql(
- enabledCacheHost?.clientId ?? 'disabled'
- ).queryKey,
- queryFn: async (): Promise<CachedGraphqlChannel[]> => {
- if (!enabledCacheHost) return [];
- return await readCachedGraphqlChannels(enabledCacheHost);
- },
- enabled: enabledCacheHost !== undefined,
- staleTime: Infinity,
- };
+ return cachedGraphqlChannelsQueryOptions(host?.disabled ? undefined : host);
});
}
diff --git a/apps/web/src/lib/queries/channel/picture.ts b/apps/web/src/lib/queries/channel/picture.ts
index fe53c10fb7..6c6cac0536 100644
--- a/apps/web/src/lib/queries/channel/picture.ts
+++ b/apps/web/src/lib/queries/channel/picture.ts
@@ -2,7 +2,7 @@ import { staticFileSizedEndpoint } from '@core/constant/servers';
import { throwOnErr } from '@core/util/result';
import { staticFileClient } from '@service-static-files/client';
import { storageServiceClient } from '@service-storage/client';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { previewDataLoader } from '../preview/dataloader';
@@ -37,24 +37,22 @@ async function waitForPictureUpload(fileId: string) {
throw new Error('Picture upload confirmation timed out');
}
+function channelPictureQueryOptions(id: string) {
+ return queryOptions({
+ queryKey: channelKeys.picture(id).queryKey,
+ queryFn: async () => {
+ const preview = await previewDataLoader.load({ id, type: 'channel' });
+ return isChannelPreviewItem(preview)
+ ? (preview.profilePictureId ?? null)
+ : null;
+ },
+ staleTime: 60_000,
+ });
+}
+
/** Reuse the batched REST preview loader, including when Soup uses GraphQL. */
export function useChannelPicture(channelId: Accessor<string>) {
- const query = useQuery(() => {
- const id = channelId();
- return {
- queryKey: channelKeys.picture(id).queryKey,
- queryFn: async () => {
- const preview = await previewDataLoader.load({
- id,
- type: 'channel',
- });
- return isChannelPreviewItem(preview)
- ? (preview.profilePictureId ?? null)
- : null;
- },
- staleTime: 60_000,
- };
- });
+ const query = useQuery(() => channelPictureQueryOptions(channelId()));
// The icon keeps its fallback while loading; it must never suspend its row.
const pictureId = () => (query.isSuccess ? query.data : null);
diff --git a/apps/web/src/lib/queries/chat.ts b/apps/web/src/lib/queries/chat.ts
index e045a50f3b..40ab03ccb1 100644
--- a/apps/web/src/lib/queries/chat.ts
+++ b/apps/web/src/lib/queries/chat.ts
@@ -1,7 +1,7 @@
import { throwOnErr } from '@core/util/result';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import { queryClient } from './client';
import { historyKeys } from './history/keys';
import { invalidatePreview } from './preview';
@@ -16,22 +16,20 @@ type ChatRenamedMessage = {
name: string;
};
-export function useChatQuery(chatId: () => string | undefined) {
- return useQuery(() => {
- const id = chatId();
-
- return {
- queryKey: ['chat', id],
- queryFn: async () =>
- throwOnErr(
- async () => await cognitionApiServiceClient.getChat({ chat_id: id! })
- ),
- staleTime: CHAT_STALE_TIME,
- enabled: !!id,
- };
+function chatQueryOptions(id: string | undefined) {
+ return queryOptions({
+ queryKey: ['chat', id],
+ queryFn: () =>
+ throwOnErr(() => cognitionApiServiceClient.getChat({ chat_id: id! })),
+ staleTime: CHAT_STALE_TIME,
+ enabled: !!id,
});
}
+export function useChatQuery(chatId: () => string | undefined) {
+ return useQuery(() => chatQueryOptions(chatId()));
+}
+
export function useChatRenameWebsocketSync() {
createConnectionWebsocketEffect((message) => {
if (message.type !== CHAT_RENAMED_MESSAGE_TYPE) return;
diff --git a/apps/web/src/lib/queries/claude-auth/connection.ts b/apps/web/src/lib/queries/claude-auth/connection.ts
index 74076316a5..48074eb022 100644
--- a/apps/web/src/lib/queries/claude-auth/connection.ts
+++ b/apps/web/src/lib/queries/claude-auth/connection.ts
@@ -1,6 +1,6 @@
import { throwOnErr } from '@core/util/result';
import { claudeAuthClient } from '@service-agent-harness/claude-auth';
-import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import { queryOptions, useQuery, useQueryClient } from '@tanstack/solid-query';
import type { ClaudeConnectionSource } from '../../../features/claude-connection/core/connection';
import { claudeAuthKeys } from './keys';
@@ -9,14 +9,25 @@ export function useClaudeConnectionStatusQuery(
owner: () => string | undefined,
enabled: () => boolean = () => true
) {
- return useQuery(() => ({
- queryKey: claudeAuthKeys.status(owner()).queryKey,
- queryFn: ({ signal }) => throwOnErr(() => claudeAuthClient.status(signal)),
- enabled: !!owner() && enabled(),
+ return useQuery(() => claudeConnectionStatusQueryOptions(owner(), enabled()));
+}
+
+function fetchClaudeConnectionStatus({ signal }: { signal: AbortSignal }) {
+ return throwOnErr(() => claudeAuthClient.status(signal));
+}
+
+function claudeConnectionStatusQueryOptions(
+ owner: string | undefined,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: claudeAuthKeys.status(owner).queryKey,
+ queryFn: fetchClaudeConnectionStatus,
+ enabled: !!owner && enabled,
staleTime: 0,
gcTime: 0,
retry: false,
- }));
+ });
}
/** Only safe status is cached. One-time codes never enter a mutation cache. */
diff --git a/apps/web/src/lib/queries/cognition/chat-data.ts b/apps/web/src/lib/queries/cognition/chat-data.ts
index 8130d9fc7a..3547cd663f 100644
--- a/apps/web/src/lib/queries/cognition/chat-data.ts
+++ b/apps/web/src/lib/queries/cognition/chat-data.ts
@@ -1,5 +1,6 @@
import { catchToResult, throwOnErr } from '@core/util/result';
import { cognitionApiServiceClient } from '@service-cognition/client';
+import type { GetChatResponse } from '@service-cognition/generated/schemas/getChatResponse';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -34,10 +35,14 @@ export async function fetchAndCacheChat(chatId: string) {
);
}
+function selectChat(data: GetChatResponse) {
+ return data.chat;
+}
+
export function useChatDataQuery(chatId: Accessor<string>) {
return useQuery(() => ({
...chatQueryOptions(chatId()),
- select: (data) => data.chat,
+ select: selectChat,
enabled: !!chatId(),
}));
}
diff --git a/apps/web/src/lib/queries/create-infinite-queries.ts b/apps/web/src/lib/queries/create-infinite-queries.ts
index 9e5207ce19..46f97227e0 100644
--- a/apps/web/src/lib/queries/create-infinite-queries.ts
+++ b/apps/web/src/lib/queries/create-infinite-queries.ts
@@ -49,6 +49,26 @@ type InfiniteQueriesResult<TData, TSelect> = {
map: Accessor<Map<string, InfiniteQueryResult<TData, TSelect>>>;
};
+type PageParam = string | null;
+
+// Cached callbacks outlive the per-key root. They wrap only the caller's
+// function values, never the config lookup or this helper's scope.
+function wrapQueryFn<TData>(
+ queryFn: InfiniteQueryConfig<TData, unknown>['queryFn'] | undefined
+) {
+ return async (ctx: { pageParam: PageParam }): Promise<TData | null> =>
+ queryFn ? queryFn({ pageParam: ctx.pageParam }) : null;
+}
+
+function wrapGetNextPageParam<TData>(
+ getNextPageParam:
+ | InfiniteQueryConfig<TData, unknown>['getNextPageParam']
+ | undefined
+) {
+ return (lastPage: TData | null): PageParam =>
+ lastPage ? (getNextPageParam?.(lastPage) ?? null) : null;
+}
+
export function createInfiniteQueries<TData, TSelect = TData[]>(
getConfigs: Accessor<InfiniteQueryConfig<TData, TSelect>[]>
): InfiniteQueriesResult<TData, TSelect> {
@@ -82,13 +102,11 @@ export function createInfiniteQueries<TData, TSelect = TData[]>(
return {
queryKey: config?.queryKey ?? (['__disabled__', key] as const),
- queryFn: async (ctx) => {
- if (!config) return null;
- return config.queryFn({ pageParam: ctx.pageParam });
- },
+ queryFn: wrapQueryFn<TData>(config?.queryFn),
initialPageParam: null,
- getNextPageParam: (lastPage) =>
- lastPage ? (config?.getNextPageParam(lastPage) ?? null) : null,
+ getNextPageParam: wrapGetNextPageParam<TData>(
+ config?.getNextPageParam
+ ),
enabled: config?.enabled ?? false,
staleTime: config?.staleTime ?? Infinity,
initialData: config?.initialData as InfiniteData<
diff --git a/apps/web/src/lib/queries/email/backfill.ts b/apps/web/src/lib/queries/email/backfill.ts
index 563e353d95..444f513fe1 100644
--- a/apps/web/src/lib/queries/email/backfill.ts
+++ b/apps/web/src/lib/queries/email/backfill.ts
@@ -106,6 +106,10 @@ export function estimateEtaSeconds(
return threadsLeft / ratePerMs / 1000;
}
+function fetchBackfillJobs() {
+ return throwOnErr(() => emailClient.listBackfillJobs());
+}
+
/**
* Lists every backfill job for the user. Fired when the email settings open, to
* surface COMPLETED backfills. In-progress backfills are driven by the live
@@ -116,8 +120,7 @@ export function estimateEtaSeconds(
export function useBackfillJobsQuery() {
return useQuery(() => ({
queryKey: emailKeys.backfillJobs.queryKey,
- queryFn: async () =>
- throwOnErr(async () => await emailClient.listBackfillJobs()),
+ queryFn: fetchBackfillJobs,
}));
}
diff --git a/apps/web/src/lib/queries/email/link.ts b/apps/web/src/lib/queries/email/link.ts
index c3df5d5ca7..484630f4ab 100644
--- a/apps/web/src/lib/queries/email/link.ts
+++ b/apps/web/src/lib/queries/email/link.ts
@@ -29,20 +29,26 @@ const queryEnabled = () => true;
export function useInboxHealthProbeQuery() {
return useQuery(() => ({
queryKey: emailKeys.linksHealthProbe.queryKey,
- queryFn: async () => {
- await emailClient.healthCheckLinks();
- return null;
- },
+ queryFn: probeInboxHealth,
staleTime: HEALTH_PROBE_STALE_TIME,
refetchOnWindowFocus: true,
retry: false,
}));
}
+async function probeInboxHealth() {
+ await emailClient.healthCheckLinks();
+ return null;
+}
+
+function fetchEmailLinks() {
+ return throwOnErr(() => emailClient.getLinks());
+}
+
export function useEmailLinksQuery(enabled: Accessor<boolean> = queryEnabled) {
return useQuery(() => ({
queryKey: emailKeys.links.queryKey,
- queryFn: async () => throwOnErr(async () => await emailClient.getLinks()),
+ queryFn: fetchEmailLinks,
enabled: enabled(),
staleTime: LINK_STALE_TIME,
refetchOnWindowFocus: 'always',
diff --git a/apps/web/src/lib/queries/favorites/favorites.ts b/apps/web/src/lib/queries/favorites/favorites.ts
index 55b474aace..c126c90b8e 100644
--- a/apps/web/src/lib/queries/favorites/favorites.ts
+++ b/apps/web/src/lib/queries/favorites/favorites.ts
@@ -10,7 +10,7 @@ import type { Favorite } from '@service-storage/generated/schemas/favorite';
import type { FavoritesList } from '@service-storage/generated/schemas/favoritesList';
import type { ListFavoritesParams } from '@service-storage/generated/schemas/listFavoritesParams';
import type { ReorderFavoritesResult } from '@service-storage/graphql-favorites';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -85,15 +85,20 @@ export function useFavoritesQuery(filter?: FavoritesFilter) {
return createRestFavoritesQuery(filter);
}
-function createRestFavoritesQuery(filter?: FavoritesFilter) {
- return useQuery(() => ({
+// Cached callbacks outlive the hook; only the plain filter enters this closure.
+function restFavoritesQueryOptions(filter?: FavoritesFilter) {
+ return queryOptions({
queryKey: favoriteKeys.list(filter).queryKey,
queryFn: async () =>
await throwOnErr(() =>
storageServiceClient.favorites.getFavorites(filter)
),
staleTime: 60_000,
- }));
+ });
+}
+
+function createRestFavoritesQuery(filter?: FavoritesFilter) {
+ return useQuery(() => restFavoritesQueryOptions(filter));
}
/**
diff --git a/apps/web/src/lib/queries/gtm-invite/links.ts b/apps/web/src/lib/queries/gtm-invite/links.ts
index ce051a9e7a..9ba6f0952e 100644
--- a/apps/web/src/lib/queries/gtm-invite/links.ts
+++ b/apps/web/src/lib/queries/gtm-invite/links.ts
@@ -9,7 +9,7 @@ import { authServiceClient } from '@service-auth/client';
import type { CreateGtmInviteLinkRequest } from '@service-auth/generated/schemas/createGtmInviteLinkRequest';
import type { GtmInviteLink } from '@service-auth/generated/schemas/gtmInviteLink';
import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -22,17 +22,20 @@ export type { GtmInviteLink, GtmInviteOffer };
const LINKS_REFETCH_INTERVAL_MS = 30_000;
const OFFER_STALE_TIME_MS = 60_000;
-/** Staff dashboard: every staff member's links, or just the caller's. */
-export function useGtmInviteLinksQuery(mine: Accessor<boolean>) {
- return useQuery(() => ({
- queryKey: gtmInviteKeys.links(mine()).queryKey,
+// Cached callbacks outlive the hooks; only plain values enter these closures.
+function gtmInviteLinksQueryOptions(mine: boolean) {
+ return queryOptions({
+ queryKey: gtmInviteKeys.links(mine).queryKey,
queryFn: async () =>
- await throwOnErr(() =>
- authServiceClient.listGtmInviteLinks({ mine: mine() })
- ),
+ await throwOnErr(() => authServiceClient.listGtmInviteLinks({ mine })),
// Opens and signups land server-side; keep the dashboard live.
refetchInterval: LINKS_REFETCH_INTERVAL_MS,
- }));
+ });
+}
+
+/** Staff dashboard: every staff member's links, or just the caller's. */
+export function useGtmInviteLinksQuery(mine: Accessor<boolean>) {
+ return useQuery(() => gtmInviteLinksQueryOptions(mine()));
}
export function invalidateGtmInviteLinks() {
@@ -93,6 +96,19 @@ export function useRevokeGtmInviteLinkMutation(
}));
}
+function publicGtmInviteLinkQueryOptions(token: string) {
+ return queryOptions({
+ queryKey: gtmInviteKeys.publicLink(token).queryKey,
+ queryFn: async () =>
+ await throwOnErr(() => authServiceClient.resolveGtmInviteLink(token)),
+ enabled: !!token,
+ retry: false,
+ staleTime: Number.POSITIVE_INFINITY,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ });
+}
+
/**
* The public welcome page's view of a link. Every fetch counts as an "open"
* on the dashboard, so the result is pinned for the page's lifetime.
@@ -100,29 +116,24 @@ export function useRevokeGtmInviteLinkMutation(
export function usePublicGtmInviteLinkQuery(
token: Accessor<string | undefined>
) {
- return useQuery(() => ({
- queryKey: gtmInviteKeys.publicLink(token() ?? '').queryKey,
- queryFn: async () =>
- await throwOnErr(() =>
- authServiceClient.resolveGtmInviteLink(token() ?? '')
- ),
- enabled: !!token(),
- retry: false,
- staleTime: Number.POSITIVE_INFINITY,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- }));
+ return useQuery(() => publicGtmInviteLinkQueryOptions(token() ?? ''));
}
-/** The promotion the signed-in account holds from an invite link, or null. */
-export function useGtmInviteOfferQuery(options?: { enabled?: () => boolean }) {
- return useQuery(() => ({
+function gtmInviteOfferQueryOptions(enabled: boolean) {
+ return queryOptions({
queryKey: gtmInviteKeys.offer.queryKey,
queryFn: async () =>
await throwOnErr(() => authServiceClient.getGtmInviteOffer()),
- enabled: options?.enabled ? options.enabled() : true,
+ enabled,
staleTime: OFFER_STALE_TIME_MS,
- }));
+ });
+}
+
+/** The promotion the signed-in account holds from an invite link, or null. */
+export function useGtmInviteOfferQuery(options?: { enabled?: () => boolean }) {
+ return useQuery(() =>
+ gtmInviteOfferQueryOptions(options?.enabled ? options.enabled() : true)
+ );
}
export function invalidateGtmInviteOffer() {
diff --git a/apps/web/src/lib/queries/harnesses/harnesses.ts b/apps/web/src/lib/queries/harnesses/harnesses.ts
index d10f3b7472..028d89ab43 100644
--- a/apps/web/src/lib/queries/harnesses/harnesses.ts
+++ b/apps/web/src/lib/queries/harnesses/harnesses.ts
@@ -6,7 +6,7 @@ import {
type HarnessPairing,
storageServiceClient,
} from '@service-storage/client';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import { harnessKeys } from './keys';
export type ApproveHarnessPairingParams = {
@@ -20,18 +20,21 @@ export type DeleteHarnessParams = {
harnessId: string;
};
+// Cached callbacks outlive the hooks; keep hook scope out of these closures.
+const harnessesQueryOptions = queryOptions({
+ queryKey: harnessKeys.list.queryKey,
+ queryFn: async (): Promise<Harness[]> =>
+ await throwOnErr(() => storageServiceClient.getHarnesses()),
+ refetchInterval: 15_000,
+});
+
/**
* The macrod harnesses registered for the signed-in user (and their team).
* Refetched on a short interval so the connected indicator tracks the daemon
* heartbeat without a manual refresh.
*/
export function useHarnessesQuery() {
- return useQuery(() => ({
- queryKey: harnessKeys.list.queryKey,
- queryFn: async (): Promise<Harness[]> =>
- await throwOnErr(() => storageServiceClient.getHarnesses()),
- refetchInterval: 15_000,
- }));
+ return useQuery(() => harnessesQueryOptions);
}
export function invalidateHarnesses() {
@@ -46,15 +49,17 @@ export function invalidateHarnesses() {
* expired code), not a transient failure.
*/
export function useHarnessPairingQuery(code: () => string | undefined) {
- return useQuery(() => ({
- queryKey: harnessKeys.pairing(code() ?? '').queryKey,
+ return useQuery(() => harnessPairingQueryOptions(code() ?? ''));
+}
+
+function harnessPairingQueryOptions(code: string) {
+ return queryOptions({
+ queryKey: harnessKeys.pairing(code).queryKey,
queryFn: async (): Promise<HarnessPairing> =>
- await throwOnErr(() =>
- storageServiceClient.getHarnessPairing({ code: code() ?? '' })
- ),
- enabled: (code() ?? '').length > 0,
+ await throwOnErr(() => storageServiceClient.getHarnessPairing({ code })),
+ enabled: code.length > 0,
retry: false,
- }));
+ });
}
export function useApproveHarnessPairingMutation() {
diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.ts
index 06aeafc115..25134c0404 100644
--- a/apps/web/src/lib/queries/history/history.ts
+++ b/apps/web/src/lib/queries/history/history.ts
@@ -9,6 +9,7 @@ import {
} from '@service-storage/client';
import { getGraphqlSoupCacheHost } from '@service-storage/graphql-soup';
import {
+ keepPreviousData,
type QueryClient,
queryOptions,
type Updater,
@@ -98,6 +99,32 @@ type HistoryQueryKey =
| typeof historyKeys.list.queryKey
| typeof historyKeys.graphqlList.queryKey;
+type HistoryGraphqlCacheHost = NonNullable<
+ ReturnType<typeof getGraphqlSoupCacheHost>
+>;
+
+// Cached options outlive the hook. The host is the app-level cache service,
+// not component state, so the factory may close over it.
+function cachedGraphqlHistoryQueryOptions(cacheHost: HistoryGraphqlCacheHost) {
+ return {
+ queryKey: historyKeys.graphqlList.queryKey,
+ queryFn: () => readCachedGraphqlHistoryItems(cacheHost),
+ placeholderData: keepPreviousData,
+ staleTime: Infinity,
+ refetchOnMount: 'always' as const,
+ reconcile: 'id' as const,
+ };
+}
+
+const restHistoryQueryOptions = {
+ queryKey: historyKeys.list.queryKey,
+ queryFn: fetchHistory,
+ staleTime: HISTORY_STALE_TIME,
+ gcTime: HISTORY_GC_TIME,
+ placeholderData: keepPreviousData,
+ reconcile: 'id' as const,
+};
+
export function useHistoryQuery() {
const graphqlSoupFlag = useFeatureFlag(enableGraphqlSoup);
const activeQueryClient = useQueryClient();
@@ -130,25 +157,9 @@ export function useHistoryQuery() {
HistoryQueryKey
>(() => {
const cacheHost = graphqlCacheHost();
- if (cacheHost) {
- return {
- queryKey: historyKeys.graphqlList.queryKey,
- queryFn: () => readCachedGraphqlHistoryItems(cacheHost),
- placeholderData: (prev: HistoryQueryFnResult | undefined) => prev,
- staleTime: Infinity,
- refetchOnMount: 'always' as const,
- reconcile: 'id',
- };
- }
-
- return {
- queryKey: historyKeys.list.queryKey,
- queryFn: fetchHistory,
- staleTime: HISTORY_STALE_TIME,
- gcTime: HISTORY_GC_TIME,
- placeholderData: (prev: HistoryQueryFnResult | undefined) => prev,
- reconcile: 'id',
- };
+ return cacheHost
+ ? cachedGraphqlHistoryQueryOptions(cacheHost)
+ : restHistoryQueryOptions;
});
}
diff --git a/apps/web/src/lib/queries/import.ts b/apps/web/src/lib/queries/import.ts
index c4ced6fe50..6bb0d08174 100644
--- a/apps/web/src/lib/queries/import.ts
+++ b/apps/web/src/lib/queries/import.ts
@@ -18,6 +18,7 @@ import {
} from '@service-cognition/import';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import {
+ queryOptions,
type UseMutationResult,
useMutation,
useQuery,
@@ -57,6 +58,22 @@ function anythingInFlight(state: ImportState | undefined): boolean {
);
}
+function fetchImportStateFromServer() {
+ return throwOnErr(() => importClient.getState());
+}
+
+// Cached on the query past unmount; module scope keeps hook state out of it.
+function importStateQueryOptions(enabled: boolean) {
+ return queryOptions({
+ queryKey: KEYS.state,
+ queryFn: fetchImportStateFromServer,
+ enabled,
+ refetchInterval: (query) =>
+ anythingInFlight(query.state.data) ? 3_000 : 15_000,
+ placeholderData: PENDING_IMPORT_STATE,
+ });
+}
+
/** The import aggregate: gather runs plus visible ledger rows. */
export function useImportQuery(options?: { enabled?: () => boolean }) {
createConnectionWebsocketEffect((message) => {
@@ -64,14 +81,9 @@ export function useImportQuery(options?: { enabled?: () => boolean }) {
void invalidateImportState();
});
- return useQuery(() => ({
- queryKey: KEYS.state,
- queryFn: async () => throwOnErr(() => importClient.getState()),
- enabled: options?.enabled ? options.enabled() : true,
- refetchInterval: (query) =>
- anythingInFlight(query.state.data) ? 3_000 : 15_000,
- placeholderData: PENDING_IMPORT_STATE,
- }));
+ return useQuery(() =>
+ importStateQueryOptions(options?.enabled ? options.enabled() : true)
+ );
}
function invalidateImportState() {
diff --git a/apps/web/src/lib/queries/mcp-servers.ts b/apps/web/src/lib/queries/mcp-servers.ts
index 1902c85659..3544b2a49b 100644
--- a/apps/web/src/lib/queries/mcp-servers.ts
+++ b/apps/web/src/lib/queries/mcp-servers.ts
@@ -17,6 +17,12 @@ const KEYS = {
/** Stable placeholder for `neverSuspend` consumers (see below). */
const NO_SERVERS: ServerResponse[] = [];
+function fetchMcpServers() {
+ return throwOnErr(
+ async () => await cognitionApiServiceClient.listMcpServers()
+ );
+}
+
export function useMcpServersQuery(options?: {
/**
* Poll for connection changes. OAuth finishes in another tab, and if this
@@ -36,8 +42,7 @@ export function useMcpServersQuery(options?: {
}) {
return useQuery(() => ({
queryKey: KEYS.list,
- queryFn: async () =>
- throwOnErr(async () => await cognitionApiServiceClient.listMcpServers()),
+ queryFn: fetchMcpServers,
refetchOnMount: 'always' as const,
refetchOnWindowFocus: 'always' as const,
refetchInterval: options?.refetchInterval,
diff --git a/apps/web/src/lib/queries/messages/document-messages.ts b/apps/web/src/lib/queries/messages/document-messages.ts
index 0b3ce95922..a5f805d179 100644
--- a/apps/web/src/lib/queries/messages/document-messages.ts
+++ b/apps/web/src/lib/queries/messages/document-messages.ts
@@ -6,7 +6,7 @@ import {
type MessageThread,
type PostMessage,
} from '@service-storage/messages';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import { type Accessor, createEffect } from 'solid-js';
import {
newMessageId,
@@ -99,19 +99,27 @@ export function useMessageActions(parent: Accessor<MessageParent>) {
};
}
+// Cached callbacks outlive the hook; only plain request values enter here.
+function messageLinkQueryOptions(
+ parent: MessageParent,
+ target: string | null | undefined
+) {
+ return queryOptions({
+ queryKey: ['historical-comment-link', parent.type, parent.id, target],
+ enabled: !!target,
+ queryFn: () =>
+ /^\d+$/.test(target!)
+ ? entityMessagesClient.legacyLink(parent, target!)
+ : entityMessagesClient.get(parent, target!),
+ });
+}
+
/** Resolve copied links, falling back to the root when the linked reply was deleted. */
export function useMessageLink(
parent: Accessor<MessageParent>,
target: Accessor<string | null | undefined>
) {
- const legacy = useQuery(() => ({
- queryKey: ['historical-comment-link', parent().type, parent().id, target()],
- enabled: !!target(),
- queryFn: () =>
- /^\d+$/.test(target()!)
- ? entityMessagesClient.legacyLink(parent(), target()!)
- : entityMessagesClient.get(parent(), target()!),
- }));
+ const legacy = useQuery(() => messageLinkQueryOptions(parent(), target()));
return {
error: () => legacy.error,
refetch: legacy.refetch,
diff --git a/apps/web/src/lib/queries/messages/thread-replies.ts b/apps/web/src/lib/queries/messages/thread-replies.ts
index ed5e8f9789..1604f1f541 100644
--- a/apps/web/src/lib/queries/messages/thread-replies.ts
+++ b/apps/web/src/lib/queries/messages/thread-replies.ts
@@ -65,6 +65,12 @@ export function seedThreadRepliesFromMessageTimeline(
});
}
+// Cached selectors outlive mounted rows. Keep this outside the hook so its
+// closure cannot retain component accessors and detached thread DOM.
+function selectThreadReplies(thread: MessageThread) {
+ return thread.replies;
+}
+
export function useThreadRepliesQuery(
parent: Accessor<MessageParent>,
messageId: Accessor<string>,
@@ -76,7 +82,7 @@ export function useThreadRepliesQuery(
return {
...threadRepliesQueryOptions(parent(), messageId()),
enabled: enabled(),
- select: (thread: MessageThread) => thread.replies,
+ select: selectThreadReplies,
};
});
}
diff --git a/apps/web/src/lib/queries/messages/timeline.ts b/apps/web/src/lib/queries/messages/timeline.ts
index 03221c431b..746f044c85 100644
--- a/apps/web/src/lib/queries/messages/timeline.ts
+++ b/apps/web/src/lib/queries/messages/timeline.ts
@@ -16,6 +16,7 @@ import {
} from '@service-storage/messages';
import {
type InfiniteData,
+ queryOptions,
useInfiniteQuery,
useQuery,
} from '@tanstack/solid-query';
@@ -353,27 +354,32 @@ export function useMessageTimelineQuery(
}));
}
+// Cached callbacks outlive the hook; only plain request values enter here.
+function messageTimelineByIdsQueryOptions(
+ parent: MessageParent,
+ messageIds: string[]
+) {
+ return queryOptions({
+ queryKey: messageKeys.messagesByIds(parent, messageIds).queryKey,
+ queryFn: async (): Promise<MessageListItem[]> => {
+ const page = await entityMessagesClient.list(parent, {
+ ids: messageIds,
+ limit: 100,
+ });
+ return page.items.map(normalizeChannelMessageSender);
+ },
+ enabled: messageIds.length > 0,
+ staleTime: Infinity,
+ });
+}
+
export function useMessageTimelineByIdsQuery(
parent: Accessor<MessageParent>,
messageIds: Accessor<string[]>
) {
- return useQuery(() => {
- const resolvedParent = parent();
- const resolvedMessageIds = messageIds();
- return {
- queryKey: messageKeys.messagesByIds(resolvedParent, resolvedMessageIds)
- .queryKey,
- queryFn: async (): Promise<MessageListItem[]> => {
- const page = await entityMessagesClient.list(resolvedParent, {
- ids: resolvedMessageIds,
- limit: 100,
- });
- return page.items.map(normalizeChannelMessageSender);
- },
- enabled: resolvedMessageIds.length > 0,
- staleTime: Infinity,
- };
- });
+ return useQuery(() =>
+ messageTimelineByIdsQueryOptions(parent(), messageIds())
+ );
}
/** Returns the cache key for one channel message query variant. */
diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.ts
index 18a4968245..cae40fb74c 100644
--- a/apps/web/src/lib/queries/notification/user-notifications.ts
+++ b/apps/web/src/lib/queries/notification/user-notifications.ts
@@ -42,6 +42,13 @@ function stripOwnerId({
return rest;
}
+// Cached selectors outlive the hooks that pass them; keep hook scope out.
+function selectNotificationItems(
+ data: InfiniteData<GetAllUserNotificationsResponse, unknown>
+): UnifiedNotification[] {
+ return data.pages.flatMap(({ items }) => items.map(stripOwnerId));
+}
+
const DEFAULT_NOTIFICATION_LIMIT = 20;
const NOTIFICATION_STALE_TIME = 5 * 60 * 1000; // 5 minutes
const NOTIFICATION_GC_TIME = 10 * 60 * 1000; // 10 minutes
@@ -201,12 +208,7 @@ function useRestUserNotificationsQuery(
const limit = normalizeLimit(queryArgs.limit);
return {
...userNotificationsQueryOptions(limit, queryArgs.done),
- select: (
- data: InfiniteData<
- GetAllUserNotificationsResponse,
- UserNotificationsPageParam
- >
- ) => data.pages.flatMap(({ items }) => items.map(stripOwnerId)),
+ select: selectNotificationItems,
enabled: options?.().enabled,
// Always refetch in the case of a stale browser tab
refetchOnWindowFocus: 'always' as const,
@@ -341,12 +343,7 @@ function _useEntityNotificationsQuery(args: {
return useInfiniteQuery(() => ({
...entityNotificationsQueryOptions(args.eventItemId(), limit),
- select: (
- data: InfiniteData<
- GetAllUserNotificationsResponse,
- EntityNotificationsPageParam
- >
- ) => data.pages.flatMap(({ items }) => items.map(stripOwnerId)),
+ select: selectNotificationItems,
}));
}
@@ -395,12 +392,7 @@ function _useEntitiesNotificationsQuery(args: {
return useInfiniteQuery(() => ({
...entitiesNotificationsQueryOptions(args.eventItemIds(), limit),
- select: (
- data: InfiniteData<
- GetAllUserNotificationsResponse,
- EntitiesNotificationsPageParam
- >
- ) => data.pages.flatMap(({ items }) => items.map(stripOwnerId)),
+ select: selectNotificationItems,
enabled: args.eventItemIds().length > 0,
}));
}
diff --git a/apps/web/src/lib/queries/onboarding.ts b/apps/web/src/lib/queries/onboarding.ts
index 4852ecc0b4..1a11b98dc8 100644
--- a/apps/web/src/lib/queries/onboarding.ts
+++ b/apps/web/src/lib/queries/onboarding.ts
@@ -30,11 +30,15 @@ const PENDING_ONBOARDING_STATE: OnboardingState = {
connected_servers: [],
};
+function fetchOnboardingState() {
+ return throwOnErr(() => onboardingClient.getState());
+}
+
/** The onboarding row + connections. Polling keeps gather runs starting. */
export function useOnboardingQuery(options?: { enabled?: () => boolean }) {
return useQuery(() => ({
queryKey: KEYS.state,
- queryFn: async () => throwOnErr(() => onboardingClient.getState()),
+ queryFn: fetchOnboardingState,
enabled: options?.enabled ? options.enabled() : true,
refetchInterval: 12_000,
placeholderData: PENDING_ONBOARDING_STATE,
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
index 9913727009..6f3394b0c1 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -11,6 +11,7 @@ import {
} from '@service-cognition/client';
import {
type InfiniteData,
+ infiniteQueryOptions,
useInfiniteQuery,
useMutation,
useQuery,
@@ -27,6 +28,12 @@ const KEYS = {
/** Stable placeholder for `neverSuspend` consumers (see below). */
const NO_CONNECTIONS: PipedreamConnectionResponse[] = [];
+function fetchPipedreamConnections() {
+ return throwOnErr(
+ async () => await cognitionApiServiceClient.listPipedreamConnections()
+ );
+}
+
export function usePipedreamConnectionsQuery(options?: {
/**
* Poll for connection changes. Connecting finishes in the Connect UI
@@ -39,10 +46,7 @@ export function usePipedreamConnectionsQuery(options?: {
}) {
return useQuery(() => ({
queryKey: KEYS.list,
- queryFn: async () =>
- throwOnErr(
- async () => await cognitionApiServiceClient.listPipedreamConnections()
- ),
+ queryFn: fetchPipedreamConnections,
refetchOnMount: 'always' as const,
refetchOnWindowFocus: 'always' as const,
refetchInterval: options?.refetchInterval,
@@ -79,18 +83,26 @@ export function usePipedreamConnectedSlugs(options?: {
return { slugs, ready };
}
-/**
- * Browse or search the Pipedream app catalog, paged by cursor. Entries come
- * from Pipedream's app directory, ranked most-popular-first.
- */
-export function usePipedreamCatalogQuery(search: () => string) {
- return useInfiniteQuery(() => ({
- queryKey: KEYS.catalog(search().trim()),
+// Serve the previous search's results (or nothing) instead of suspending:
+// first load must not block the settings page on the directory, and
+// keystrokes must not blank the list while refetching.
+function catalogPlaceholder(
+ previous:
+ | InfiniteData<PipedreamCatalogResponse, string | undefined>
+ | undefined
+) {
+ return previous ?? { pages: [], pageParams: [] };
+}
+
+// Cached callbacks only close over the trimmed search string.
+function pipedreamCatalogQueryOptions(search: string) {
+ return infiniteQueryOptions({
+ queryKey: KEYS.catalog(search),
queryFn: async ({ pageParam }: { pageParam: string | undefined }) =>
throwOnErr(
async () =>
await cognitionApiServiceClient.browsePipedreamCatalog({
- search: search().trim() || undefined,
+ search: search || undefined,
cursor: pageParam,
})
),
@@ -98,15 +110,16 @@ export function usePipedreamCatalogQuery(search: () => string) {
getNextPageParam: (lastPage: PipedreamCatalogResponse) =>
lastPage.next_cursor ?? undefined,
staleTime: 5 * 60 * 1000,
- // Serve the previous search's results (or nothing) instead of
- // suspending: first load must not block the settings page on the
- // directory, and keystrokes must not blank the list while refetching.
- placeholderData: (
- previous:
- | InfiniteData<PipedreamCatalogResponse, string | undefined>
- | undefined
- ) => previous ?? { pages: [], pageParams: [] },
- }));
+ placeholderData: catalogPlaceholder,
+ });
+}
+
+/**
+ * Browse or search the Pipedream app catalog, paged by cursor. Entries come
+ * from Pipedream's app directory, ranked most-popular-first.
+ */
+export function usePipedreamCatalogQuery(search: () => string) {
+ return useInfiniteQuery(() => pipedreamCatalogQueryOptions(search().trim()));
}
function invalidateConnections() {
diff --git a/apps/web/src/lib/queries/preview/preview.ts b/apps/web/src/lib/queries/preview/preview.ts
index 8ac890bf02..6e40f8ac02 100644
--- a/apps/web/src/lib/queries/preview/preview.ts
+++ b/apps/web/src/lib/queries/preview/preview.ts
@@ -8,7 +8,7 @@ import { authKeys } from '@queries/auth/keys';
import type { UserInfoData } from '@queries/auth/user-info';
import { queryReadyGate } from '@queries/gate';
import { DEFAULT_ITEM_TYPE, type ItemType } from '@service-storage/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor, Setter } from 'solid-js';
import { createMemo } from 'solid-js';
import { queryClient } from '../client';
@@ -153,6 +153,22 @@ function useItemPreviewQuery(
};
}
+// Cached callbacks must only close over plain request values, never hook state.
+function channelMessagePreviewQueryOptions(
+ itemId: string,
+ channelId: string,
+ messageId: string,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: previewKeys.item(itemId)._ctx.channelMessage(channelId, messageId)
+ .queryKey,
+ queryFn: ({ signal }) => fetchMessageContext(channelId, messageId, signal),
+ staleTime: PREVIEW_STALE_TIME,
+ enabled,
+ });
+}
+
export function useItemPreview(item: Accessor<ItemEntity>) {
const previewQuery = useItemPreviewQuery(item);
@@ -160,19 +176,15 @@ export function useItemPreview(item: Accessor<ItemEntity>) {
const item_ = item();
const channelId = item_.type === 'channel' ? item_.id : '';
const messageId = item_.type === 'channel' ? (item_.messageId ?? '') : '';
- return {
- queryKey: previewKeys
- .item(item_.id)
- ._ctx.channelMessage(channelId, messageId).queryKey,
- queryFn: ({ signal }) =>
- fetchMessageContext(channelId, messageId, signal),
- staleTime: PREVIEW_STALE_TIME,
- enabled:
- !previewQuery.usesGraphql() &&
+ return channelMessagePreviewQueryOptions(
+ item_.id,
+ channelId,
+ messageId,
+ !previewQuery.usesGraphql() &&
!!channelId &&
!!messageId &&
- previewQuery.isSuccess(),
- };
+ previewQuery.isSuccess()
+ );
});
const preview = createMemo(() => {
diff --git a/apps/web/src/lib/queries/properties/definitions.ts b/apps/web/src/lib/queries/properties/definitions.ts
index b0945fc3f9..a411d0cba5 100644
--- a/apps/web/src/lib/queries/properties/definitions.ts
+++ b/apps/web/src/lib/queries/properties/definitions.ts
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
import type { CreatePropertyDefinitionRequest } from '../../service-clients/service-properties/generated/schemas/createPropertyDefinitionRequest';
@@ -18,33 +18,35 @@ type ListPropertiesQueryParams = {
forEntityType?: EntityType;
};
+// Cached callbacks outlive the caller; only plain request values enter here.
+function listPropertiesQueryOptions(
+ { scope, includeOptions, forEntityType }: ListPropertiesQueryParams,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: propertiesKeys.definitions({
+ scope,
+ includeOptions,
+ forEntityType,
+ }).queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ propertiesServiceClient.listProperties({
+ scope,
+ include_options: includeOptions,
+ for_entity_type: forEntityType,
+ })
+ ),
+ enabled,
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ });
+}
+
export function useListPropertiesQuery(
params: Accessor<ListPropertiesQueryParams>,
enabled: Accessor<boolean> = () => true
) {
- return useQuery(() => {
- const { scope, includeOptions, forEntityType } = params();
- return {
- queryKey: propertiesKeys.definitions({
- scope,
- includeOptions,
- forEntityType,
- }).queryKey,
- queryFn: async () => {
- const data = await throwOnErr(
- async () =>
- await propertiesServiceClient.listProperties({
- scope,
- include_options: includeOptions,
- for_entity_type: forEntityType,
- })
- );
- return data;
- },
- enabled: enabled(),
- staleTime: 1000 * 60 * 5, // 5 minutes
- };
- });
+ return useQuery(() => listPropertiesQueryOptions(params(), enabled()));
}
export async function fetchPropertyDefinitionWithOptions(
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index ada20ce904..65c0d70746 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -20,7 +20,7 @@ import { isInstantiatedProperty } from '@property/utils';
import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { DeleteEntityPropertyDocument } from '@service-storage/graphql/generated/graphql';
import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import { type Accessor, batch } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
@@ -133,6 +133,25 @@ export function fetchEntityProperties(
});
}
+// Cached callbacks outlive the caller; only plain values enter here.
+function entityPropertiesQueryOptions(
+ entityType: EntityType,
+ entityId: string,
+ enabled: boolean,
+ includeMetadata: boolean
+) {
+ return queryOptions({
+ queryKey: propertiesKeys.entity({ entityType, entityId }).queryKey,
+ enabled,
+ queryFn: () => fetchRestEntityProperties(entityType, entityId),
+ select: (properties: Property[]) =>
+ includeMetadata
+ ? properties
+ : properties.filter((property) => property.isMetadata !== true),
+ staleTime: 0,
+ });
+}
+
export function useEntityPropertiesQuery(
entityType: Accessor<EntityType>,
entityId: Accessor<string>,
@@ -155,21 +174,13 @@ export function useEntityPropertiesQuery(
const restQuery = useQuery(
() => {
- const type = entityType();
const id = entityId();
- return {
- queryKey: propertiesKeys.entity({
- entityType: type,
- entityId: id,
- }).queryKey,
- enabled: !usesGraphql() && id.length > 0,
- queryFn: () => fetchRestEntityProperties(type, id),
- select: (properties: Property[]) =>
- includeMetadata
- ? properties
- : properties.filter((property) => property.isMetadata !== true),
- staleTime: 0,
- };
+ return entityPropertiesQueryOptions(
+ entityType(),
+ id,
+ !usesGraphql() && id.length > 0,
+ includeMetadata
+ );
},
() => queryClient
);
diff --git a/apps/web/src/lib/queries/properties/options.ts b/apps/web/src/lib/queries/properties/options.ts
index db90591558..b3ad33b947 100644
--- a/apps/web/src/lib/queries/properties/options.ts
+++ b/apps/web/src/lib/queries/properties/options.ts
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
import type { AddPropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/addPropertyOptionRequest';
@@ -14,29 +14,31 @@ import { propertiesKeys } from './keys';
// with undefined data under an app-shell Suspense boundary would remount-loop.
const EMPTY_OPTIONS: PropertyOption[] = [];
+function propertyOptionsQueryOptions(
+ propertyDefinitionId: string,
+ enabled: boolean
+) {
+ return queryOptions({
+ queryKey: propertiesKeys.options({ propertyDefinitionId }).queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ propertiesServiceClient.getPropertyOptions({
+ definition_id: propertyDefinitionId,
+ })
+ ),
+ enabled,
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ placeholderData: EMPTY_OPTIONS,
+ });
+}
+
export function usePropertyOptionsQuery(
propertyDefinitionId: Accessor<string>,
enabled: Accessor<boolean> = () => true
) {
- return useQuery(() => {
- const defId = propertyDefinitionId();
- return {
- queryKey: propertiesKeys.options({ propertyDefinitionId: defId })
- .queryKey,
- queryFn: async () => {
- const result = await throwOnErr(
- async () =>
- await propertiesServiceClient.getPropertyOptions({
- definition_id: defId,
- })
- );
- return result;
- },
- enabled: enabled(),
- staleTime: 1000 * 60 * 5, // 5 minutes
- placeholderData: EMPTY_OPTIONS,
- };
- });
+ return useQuery(() =>
+ propertyOptionsQueryOptions(propertyDefinitionId(), enabled())
+ );
}
function invalidatePropertyOptions(propertyDefinitionId: string) {
diff --git a/apps/web/src/lib/queries/properties/tags.ts b/apps/web/src/lib/queries/properties/tags.ts
index 5b9fbefde7..f3614be651 100644
--- a/apps/web/src/lib/queries/properties/tags.ts
+++ b/apps/web/src/lib/queries/properties/tags.ts
@@ -18,13 +18,16 @@ import { propertiesKeys } from './keys';
const EMPTY_TAG_SETS: TagSetResponse[] = [];
+function fetchTags() {
+ return throwOnErr(() => propertiesServiceClient.listTags());
+}
+
/** The caller's tag sets: their personal set, plus their team's set when on a team. */
export function useTagsQuery() {
const isAuthenticated = useIsAuthenticated();
return useQuery(() => ({
queryKey: propertiesKeys.tags.queryKey,
- queryFn: async () =>
- await throwOnErr(async () => await propertiesServiceClient.listTags()),
+ queryFn: fetchTags,
staleTime: 1000 * 60 * 5,
enabled: isAuthenticated() === true,
placeholderData: EMPTY_TAG_SETS,
diff --git a/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts b/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
index 3d6f118335..3ddbaa3619 100644
--- a/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
+++ b/apps/web/src/lib/queries/soup/grouped/create-grouped-soup-queries.ts
@@ -70,6 +70,43 @@ export type CreateGroupedSoupQueriesArgs = {
}>;
};
+// Retained by the query cache after the group unmounts: plain snapshots only.
+function groupPageQueryFn(input: {
+ initialPage: GroupQueryPage;
+ field: GroupByField;
+ groupKey: string;
+ soupParams: SoupParams;
+ soupBody: SoupAstBody;
+}) {
+ return async (ctx: { pageParam: string | null }): Promise<GroupQueryPage> => {
+ if (ctx.pageParam == null) {
+ return input.initialPage;
+ }
+
+ const response = await throwOnErr(async () =>
+ storageServiceClient.getGroupedSoupAstGroupPage({
+ params: {
+ cursor: ctx.pageParam,
+ group_by: serializeGroupByField(input.field),
+ group_key: input.groupKey,
+ limit: input.soupParams.limit,
+ sort_method: groupedSortMethod(input.soupParams.sort_method),
+ },
+ body: input.soupBody,
+ })
+ );
+
+ return {
+ items: response.items,
+ group: parseGroupMeta(response.group),
+ };
+ };
+}
+
+function getNextGroupPageParam(lastPage: GroupQueryPage): string | null {
+ return lastPage.group.nextCursor;
+}
+
export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
const usesGraphql = () => args.transport() === 'graphql';
const instructionsIdQuery = useInstructionsMdIdQuery();
@@ -132,6 +169,8 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
}
const options = args.queryOptions();
+ const soupParams = args.soupParams();
+ const soupBody = args.soupBody();
return initialGroupedPage.groups.map((group) => {
const initialPage = makeInitialPage(initialGroupedPage, group);
@@ -139,37 +178,19 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
return {
key: group.key,
queryKey: soupKeys.groupedGroup({
- params: args.soupParams(),
- body: args.soupBody(),
+ params: soupParams,
+ body: soupBody,
groupBy: field,
groupKey: group.key,
}).queryKey,
- queryFn: async (ctx: { pageParam: string | null }) => {
- if (ctx.pageParam == null) {
- return initialPage;
- }
-
- const response = await throwOnErr(async () =>
- storageServiceClient.getGroupedSoupAstGroupPage({
- params: {
- cursor: ctx.pageParam,
- group_by: serializeGroupByField(field),
- group_key: group.key,
- limit: args.soupParams().limit,
- sort_method: groupedSortMethod(args.soupParams().sort_method),
- },
- body: args.soupBody(),
- })
- );
-
- return {
- items: response.items,
- group: parseGroupMeta(response.group),
- };
- },
- getNextPageParam: (lastPage: GroupQueryPage): string | null => {
- return lastPage.group.nextCursor;
- },
+ queryFn: groupPageQueryFn({
+ initialPage,
+ field,
+ groupKey: group.key,
+ soupParams,
+ soupBody,
+ }),
+ getNextPageParam: getNextGroupPageParam,
select: (pages: GroupQueryPage[]) =>
combineGroupPages(pages, options.meta?.itemFilter),
initialData: {
diff --git a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts b/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts
index 15c5ca22c2..b0e18f7209 100644
--- a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts
+++ b/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts
@@ -69,6 +69,7 @@ vi.mock('@service-storage/client', () => ({
storageServiceClient: { getSoupItems: vi.fn(), getSoupAstItems: fetchSoup },
}));
vi.mock('@tanstack/solid-query', () => ({
+ infiniteQueryOptions: vi.fn((options: unknown) => options),
useInfiniteQuery: vi.fn(() => ({
data: undefined,
error: null,
diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.ts
index 46c3e95b72..6f6223b2ab 100644
--- a/apps/web/src/lib/queries/soup/items.ts
+++ b/apps/web/src/lib/queries/soup/items.ts
@@ -27,6 +27,8 @@ import type { PostSoupAstRequestAllOf } from '@service-storage/generated/schemas
import type { PostSoupRequest } from '@service-storage/generated/schemas/postSoupRequest';
import {
type InfiniteData,
+ infiniteQueryOptions,
+ keepPreviousData,
type StaleTime,
useInfiniteQuery,
} from '@tanstack/solid-query';
@@ -119,224 +121,245 @@ export type SoupAstItemsData = {
itemsById?: SoupAstItemsGroupedPage['items'];
};
-export const useSoupItemsQuery = (
- args: Accessor<SoupItemsQueryArgs>,
- options?: Accessor<SoupItemsQueryOptions>
-) => {
- const instructionsIdQuery = useInstructionsMdIdQuery();
-
- const itemFilter: SoupApiItemFilter = (item: SoupApiItem) => {
- const body = args().body;
- if (!body) return true;
- return filterSoupItemByRequestBody(item, body);
- };
-
- return useInfiniteQuery(() => ({
- queryKey: soupKeys.items(args()).queryKey,
- queryFn: async (ctx) => {
- const { params, body } = args();
-
- return throwOnErr(
- async () =>
- await storageServiceClient.getSoupItems({
- params: { cursor: ctx.pageParam },
- body: {
- ...body,
- ...params,
- },
- })
- );
- },
+// Cached options outlive the view. Keep its accessors and query proxies out.
+function soupItemsQueryOptions(
+ args: SoupItemsQueryArgs,
+ enabled: boolean | undefined,
+ staleTime: StaleTime | undefined,
+ instructionsId: string | null | undefined,
+ showSupportedForeignEntities: boolean | undefined
+) {
+ const { params, body } = args;
+ return infiniteQueryOptions({
+ queryKey: soupKeys.items(args).queryKey,
+ queryFn: (ctx) =>
+ throwOnErr(() =>
+ storageServiceClient.getSoupItems({
+ params: { cursor: ctx.pageParam },
+ body: { ...body, ...params },
+ })
+ ),
initialPageParam: null as string | null,
- getNextPageParam: (lastPage) => {
- return lastPage.next_cursor;
- },
- select: (data) => {
- return data.pages.flatMap((page) => {
- return mapSoupPageToEntityList(page, {
- instructionsIdQuery,
- showSupportedForeignEntities:
- options?.().showSupportedForeignEntities,
- });
- });
+ getNextPageParam: (lastPage) => lastPage.next_cursor,
+ select: (data) =>
+ data.pages.flatMap((page) =>
+ mapSoupPageToEntityList(page, {
+ instructionsIdQuery: { isSuccess: true, data: instructionsId },
+ showSupportedForeignEntities,
+ })
+ ),
+ enabled,
+ staleTime,
+ placeholderData: keepPreviousData,
+ meta: {
+ itemFilter: (item: SoupApiItem) =>
+ !body || filterSoupItemByRequestBody(item, body),
+ normalize: true,
},
- enabled: options?.().enabled,
- staleTime: options?.().staleTime,
- placeholderData: (p) => p,
- meta: { itemFilter, normalize: true },
- }));
-};
+ });
+}
-/** REST implementation kept private behind {@link useSoupAstItemsQuery}. */
-const useRestSoupAstItemsQuery = (
- args: Accessor<SoupAstItemsQueryArgs>,
+export const useSoupItemsQuery = (
+ args: Accessor<SoupItemsQueryArgs>,
options?: Accessor<SoupItemsQueryOptions>
) => {
const instructionsIdQuery = useInstructionsMdIdQuery();
+ return useInfiniteQuery(() =>
+ soupItemsQueryOptions(
+ args(),
+ options?.().enabled,
+ options?.().staleTime,
+ instructionsIdQuery.isSuccess ? instructionsIdQuery.data : undefined,
+ options?.().showSupportedForeignEntities
+ )
+ );
+};
- return useInfiniteQuery(() => {
- const { params, body, groupBy, transport } = args();
+type RestSoupAstItemsMeta = SoupItemsQueryOptions['meta'];
+
+async function fetchRestSoupAstItemsPage(
+ { params, body, groupBy }: SoupAstItemsQueryArgs,
+ cursor: string | null,
+ requestSignal: AbortSignal
+): Promise<SoupAstItemsPage> {
+ const signal = createSoupRequestSignal(requestSignal);
+
+ if (groupBy) {
+ const sort_method = groupedSortMethod(params.sort_method);
+
+ const response = await throwOnErr(
+ async () =>
+ await storageServiceClient.getGroupedSoupAstItems({
+ params: {
+ group_by: serializeGroupByField(groupBy),
+ per_group_limit: params.limit,
+ sort_method,
+ },
+ body,
+ signal,
+ })
+ );
return {
- queryKey: soupKeys.astItems({ params, body, groupBy, transport })
- .queryKey,
- queryFn: async (ctx): Promise<SoupAstItemsPage> => {
- const signal = createSoupRequestSignal(ctx.signal);
-
- if (groupBy) {
- const sort_method = groupedSortMethod(params.sort_method);
-
- const fetchRest = async () => {
- const response = await throwOnErr(
- async () =>
- await storageServiceClient.getGroupedSoupAstItems({
- params: {
- group_by: serializeGroupByField(groupBy),
- per_group_limit: params.limit,
- sort_method,
- },
- body,
- signal,
- })
- );
-
- return {
- items: response.items,
- groups: response.groups.map(parseGroupMeta),
- };
- };
-
- const response = await fetchRest();
-
- return {
- kind: 'grouped',
- items: response.items,
- groups: response.groups,
- nextCursor: null,
- };
- }
+ kind: 'grouped',
+ items: response.items,
+ groups: response.groups.map(parseGroupMeta),
+ nextCursor: null,
+ };
+ }
+
+ const response = await throwOnErr(
+ async () =>
+ await storageServiceClient.getSoupAstItems({
+ params: { cursor },
+ body: {
+ ...body,
+ ...params,
+ },
+ signal,
+ })
+ );
- const fetchRest = () =>
- throwOnErr(
- async () =>
- await storageServiceClient.getSoupAstItems({
- params: {
- cursor: ctx.pageParam,
- },
- body: {
- ...body,
- ...params,
- },
- signal,
- })
- );
-
- const response = await fetchRest();
+ return {
+ kind: 'flat',
+ items: response.items,
+ nextCursor: response.next_cursor ?? null,
+ oldestFetchedTimestamp: soupPageTimestamp(
+ response.items.map(mapApiSoupItemToEntity),
+ params.sort_method
+ ),
+ };
+}
- return {
- kind: 'flat',
- items: response.items,
- nextCursor: response.next_cursor ?? null,
- oldestFetchedTimestamp: soupPageTimestamp(
- response.items.map(mapApiSoupItemToEntity),
- params.sort_method
- ),
- };
- },
- initialPageParam: null as string | null,
- getNextPageParam: (lastPage): string | null => {
- if (lastPage.kind === 'grouped') return null;
- return lastPage.nextCursor;
- },
- select: (data): SoupAstItemsData => {
- const firstPage = data.pages[0];
-
- if (firstPage?.kind === 'grouped') {
- const groups = firstPage.groups
- .slice()
- .sort(makeGroupComparator(groupBy));
-
- const itemsById = firstPage.items;
- const entities: EntityData[] = [];
-
- for (const g of groups) {
- for (const id of g.itemIds) {
- const item = itemsById[id];
-
- let displayable = false;
-
- if (item.tag === 'foreignEntity') {
- displayable =
- options?.().showSupportedForeignEntities === true &&
- item.data.foreignEntitySource === 'github_pull_request';
- } else {
- displayable =
- item && !isInstructionsMdDoc(item, instructionsIdQuery);
- }
- if (displayable && isDisplayableSoupItem(item)) {
- const mapped = mapApiSoupItemToEntity(item);
- entities.push(mapped);
- }
+function getNextRestSoupAstPageParam(
+ lastPage: SoupAstItemsPage
+): string | null {
+ if (lastPage.kind === 'grouped') return null;
+ return lastPage.nextCursor;
+}
+
+// Cached options outlive the view. Only plain snapshots enter here: no view
+// accessors, option accessors, or query proxies.
+function restSoupAstItemsQueryOptions(
+ args: SoupAstItemsQueryArgs,
+ enabled: boolean | undefined,
+ staleTime: StaleTime | undefined,
+ meta: RestSoupAstItemsMeta,
+ instructionsId: string | null | undefined,
+ showSupportedForeignEntities: boolean | undefined
+) {
+ const { params, body, groupBy, transport } = args;
+ const instructionsIdQuery = { isSuccess: true, data: instructionsId };
+
+ return infiniteQueryOptions({
+ queryKey: soupKeys.astItems({ params, body, groupBy, transport }).queryKey,
+ queryFn: (ctx) =>
+ fetchRestSoupAstItemsPage(args, ctx.pageParam, ctx.signal),
+ initialPageParam: null as string | null,
+ getNextPageParam: getNextRestSoupAstPageParam,
+ select: (data): SoupAstItemsData => {
+ const firstPage = data.pages[0];
+
+ if (firstPage?.kind === 'grouped') {
+ const groups = firstPage.groups
+ .slice()
+ .sort(makeGroupComparator(groupBy));
+
+ const itemsById = firstPage.items;
+ const entities: EntityData[] = [];
+
+ for (const g of groups) {
+ for (const id of g.itemIds) {
+ const item = itemsById[id];
+
+ let displayable = false;
+
+ if (item.tag === 'foreignEntity') {
+ displayable =
+ showSupportedForeignEntities === true &&
+ item.data.foreignEntitySource === 'github_pull_request';
+ } else {
+ displayable =
+ item && !isInstructionsMdDoc(item, instructionsIdQuery);
+ }
+ if (displayable && isDisplayableSoupItem(item)) {
+ const mapped = mapApiSoupItemToEntity(item);
+ entities.push(mapped);
}
}
-
- return { entities, groups, itemsById };
}
- const entities = data.pages.flatMap((page) => {
- if (page.kind !== 'flat') return [];
+ return { entities, groups, itemsById };
+ }
- return mapSoupPageToEntityList(
- { items: page.items, next_cursor: null },
- {
- instructionsIdQuery,
- showSupportedForeignEntities:
- options?.().showSupportedForeignEntities,
- }
- );
- });
+ const entities = data.pages.flatMap((page) => {
+ if (page.kind !== 'flat') return [];
- const pageTimestamps = data.pages.flatMap((page) =>
- page.kind === 'flat' && page.oldestFetchedTimestamp !== undefined
- ? [page.oldestFetchedTimestamp]
- : []
+ return mapSoupPageToEntityList(
+ { items: page.items, next_cursor: null },
+ { instructionsIdQuery, showSupportedForeignEntities }
);
- return {
- entities,
- groups: undefined,
- oldestFetchedTimestamp:
- pageTimestamps.length > 0 ? Math.min(...pageTimestamps) : undefined,
- };
- },
- enabled: options?.().enabled !== false && !options?.().networkPaused,
- // Do not spin through background retries while the explicit load-error
- // state is visible. NWPathMonitor lets TanStack pause an offline query
- // and resume it automatically when the path becomes available again.
- ...SOUP_NETWORK_QUERY_OPTIONS,
- // A timed-out native request should reach the view's load-error state.
- // Retry remains available explicitly from that state.
- staleTime: options?.().staleTime,
- placeholderData: (prev, prevQuery) => {
- // Keep the previous rows on screen while params/filters change, but
- // not across a grouping switch — the old groups would render under
- // the new grouping (e.g. status groups while assignee groups load).
- const prevGroupBy = (
- prevQuery?.meta as SoupItemsQueryOptions['meta'] | undefined
- )?.groupBy;
-
- if (JSON.stringify(prevGroupBy) !== JSON.stringify(groupBy)) {
- return undefined;
- }
+ });
- return prev;
- },
- meta: {
- ...options?.().meta,
- groupBy,
- normalize: true,
- },
- };
+ const pageTimestamps = data.pages.flatMap((page) =>
+ page.kind === 'flat' && page.oldestFetchedTimestamp !== undefined
+ ? [page.oldestFetchedTimestamp]
+ : []
+ );
+ return {
+ entities,
+ groups: undefined,
+ oldestFetchedTimestamp:
+ pageTimestamps.length > 0 ? Math.min(...pageTimestamps) : undefined,
+ };
+ },
+ enabled,
+ // Do not spin through background retries while the explicit load-error
+ // state is visible. NWPathMonitor lets TanStack pause an offline query
+ // and resume it automatically when the path becomes available again.
+ ...SOUP_NETWORK_QUERY_OPTIONS,
+ // A timed-out native request should reach the view's load-error state.
+ // Retry remains available explicitly from that state.
+ staleTime,
+ placeholderData: (prev, prevQuery) => {
+ // Keep the previous rows on screen while params/filters change, but
+ // not across a grouping switch — the old groups would render under
+ // the new grouping (e.g. status groups while assignee groups load).
+ const prevGroupBy = (
+ prevQuery?.meta as SoupItemsQueryOptions['meta'] | undefined
+ )?.groupBy;
+
+ if (JSON.stringify(prevGroupBy) !== JSON.stringify(groupBy)) {
+ return undefined;
+ }
+
+ return prev;
+ },
+ meta: {
+ ...meta,
+ groupBy,
+ normalize: true,
+ },
});
+}
+
+/** REST implementation kept private behind {@link useSoupAstItemsQuery}. */
+const useRestSoupAstItemsQuery = (
+ args: Accessor<SoupAstItemsQueryArgs>,
+ options?: Accessor<SoupItemsQueryOptions>
+) => {
+ const instructionsIdQuery = useInstructionsMdIdQuery();
+
+ return useInfiniteQuery(() =>
+ restSoupAstItemsQueryOptions(
+ args(),
+ options?.().enabled !== false && !options?.().networkPaused,
+ options?.().staleTime,
+ options?.().meta,
+ instructionsIdQuery.isSuccess ? instructionsIdQuery.data : undefined,
+ options?.().showSupportedForeignEntities
+ )
+ );
};
/** Transport selected by the Soup AST query facade. */
diff --git a/apps/web/src/lib/queries/soup/recently-viewed.ts b/apps/web/src/lib/queries/soup/recently-viewed.ts
index 79d10fa199..96f1743f16 100644
--- a/apps/web/src/lib/queries/soup/recently-viewed.ts
+++ b/apps/web/src/lib/queries/soup/recently-viewed.ts
@@ -2,7 +2,11 @@ import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filter
import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
-import { useQuery } from '@tanstack/solid-query';
+import {
+ keepPreviousData,
+ queryOptions,
+ useQuery,
+} from '@tanstack/solid-query';
import { queryClient } from '../client';
import type { SoupItemsQueryArgs } from './items';
import { soupKeys } from './keys';
@@ -44,52 +48,56 @@ function recentlyViewedQueryKey() {
return soupKeys.items(buildRecentlyViewedArgs()).queryKey;
}
-export function useRecentlyViewedSoupQuery() {
- return useQuery(() => {
- const args = buildRecentlyViewedArgs();
- return {
- queryKey: soupKeys.items(args).queryKey,
- queryFn: async (): Promise<RecentlyViewedItem[]> => {
- const page = await throwOnErr(
- async () =>
- await storageServiceClient.getSoupItems({
- params: {},
- body: {
- ...args.body,
- ...args.params,
- },
- })
- );
- return page.items.flatMap((item): RecentlyViewedItem[] => {
- // Reminders have no `viewedAt` — they are never "viewed", only fired.
- if (
- item.tag === 'call' ||
- item.tag === 'foreignEntity' ||
- item.tag === 'channelThread' ||
- item.tag === 'calendarEvent' ||
- item.tag === 'databaseRow'
- ) {
- return [];
- }
+async function fetchRecentlyViewed(
+ args: SoupItemsQueryArgs
+): Promise<RecentlyViewedItem[]> {
+ const page = await throwOnErr(() =>
+ storageServiceClient.getSoupItems({
+ params: {},
+ body: {
+ ...args.body,
+ ...args.params,
+ },
+ })
+ );
+ return page.items.flatMap((item): RecentlyViewedItem[] => {
+ // Reminders have no `viewedAt` — they are never "viewed", only fired.
+ if (
+ item.tag === 'call' ||
+ item.tag === 'foreignEntity' ||
+ item.tag === 'channelThread' ||
+ item.tag === 'calendarEvent' ||
+ item.tag === 'databaseRow'
+ ) {
+ return [];
+ }
- return [
- {
- id: item.tag === 'channel' ? item.data.channel.id : item.data.id,
- viewedAt:
- (item.tag === 'channel'
- ? item.data.viewed_at
- : item.data.viewedAt) ?? undefined,
- },
- ];
- });
+ return [
+ {
+ id: item.tag === 'channel' ? item.data.channel.id : item.data.id,
+ viewedAt:
+ (item.tag === 'channel' ? item.data.viewed_at : item.data.viewedAt) ??
+ undefined,
},
- staleTime: RECENTLY_VIEWED_STALE_TIME,
- gcTime: RECENTLY_VIEWED_GC_TIME,
- placeholderData: (prev) => prev,
- };
+ ];
+ });
+}
+
+// Cached callbacks outlive the caller; only the plain request enters here.
+function recentlyViewedQueryOptions(args: SoupItemsQueryArgs) {
+ return queryOptions({
+ queryKey: soupKeys.items(args).queryKey,
+ queryFn: () => fetchRecentlyViewed(args),
+ staleTime: RECENTLY_VIEWED_STALE_TIME,
+ gcTime: RECENTLY_VIEWED_GC_TIME,
+ placeholderData: keepPreviousData,
});
}
+export function useRecentlyViewedSoupQuery() {
+ return useQuery(() => recentlyViewedQueryOptions(buildRecentlyViewedArgs()));
+}
+
export function updateRecentlyViewedItem(itemId: string, viewedAt?: string) {
queryClient.setQueryData<RecentlyViewedItem[]>(
recentlyViewedQueryKey(),
diff --git a/apps/web/src/lib/queries/soup/search.ts b/apps/web/src/lib/queries/soup/search.ts
index 7a278ef670..14c59f3721 100644
--- a/apps/web/src/lib/queries/soup/search.ts
+++ b/apps/web/src/lib/queries/soup/search.ts
@@ -4,15 +4,19 @@ import { throwOnErr } from '@core/util/result';
import type { ChannelMessageEntity, EntityData, WithSearch } from '@entity';
import { soupKeys } from '@queries/soup/keys';
import {
+ createSearchResponseItemMapper,
mapChannelSearchResultItem,
- useSearchResponseItemMapper,
} from '@queries/soup/transform-utils';
import {
type ChannelSearchRequest,
searchClient,
} from '@service-search/client';
import type { UnifiedSearchRequest } from '@service-search/generated/models';
-import { useInfiniteQuery } from '@tanstack/solid-query';
+import {
+ infiniteQueryOptions,
+ keepPreviousData,
+ useInfiniteQuery,
+} from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
export type SearchSoupQueryArgs = {
@@ -32,34 +36,15 @@ export const validateSearchServiceText = (text: string) => {
return text.length >= 3;
};
-export const useSearchSoupQuery = (
- args: Accessor<SearchSoupQueryArgs>,
- options?: Accessor<SearchQueryOptions>
-) => {
- const pageSize = createMemo(() => args().params.page_size);
-
- const request = createMemo(() => {
- const body = args().body;
- return {
- ...body,
- query: body.query?.trim(),
- };
- });
-
- const validSearch = createMemo(() => {
- return validateSearchServiceText(request().query);
- });
-
- const enabled = createMemo(() => {
- if (options?.().enabled === false) return false;
-
- return ENABLE_SEARCH_SERVICE && validSearch();
- });
-
- const mapSearchResponseItem = useSearchResponseItemMapper();
-
- return useInfiniteQuery(() => ({
- queryKey: soupKeys.search({ params: args().params, body: request() })
+// Only plain request values and channel names enter the cached callbacks.
+function searchSoupQueryOptions(
+ args: SearchSoupQueryArgs,
+ channels: ReadonlyArray<{ id: string; name?: string | null }>,
+ enabled: boolean
+) {
+ const mapSearchResponseItem = createSearchResponseItemMapper(channels);
+ return infiniteQueryOptions({
+ queryKey: soupKeys.search({ params: args.params, body: args.body })
.queryKey,
queryFn: async (ctx) => {
return throwOnErr(
@@ -67,7 +52,7 @@ export const useSearchSoupQuery = (
await searchClient.search(
{
params: ctx.pageParam,
- request: { ...request() },
+ request: { ...args.body },
},
{ signal: ctx.signal }
)
@@ -75,52 +60,33 @@ export const useSearchSoupQuery = (
},
initialPageParam: {
cursor: null as string | null,
- page_size: pageSize(),
+ page_size: args.params.page_size,
},
getNextPageParam: (lastPage) => {
if (!lastPage.next_cursor) return;
return {
cursor: lastPage.next_cursor,
- page_size: pageSize(),
+ page_size: args.params.page_size,
};
},
select: (data) => {
- const searchQuery = request().query;
+ const searchQuery = args.body.query;
return data.pages.flatMap((page) => {
return page.results
.flatMap((result) => mapSearchResponseItem(result, searchQuery))
.filter((entity): entity is WithSearch<EntityData> => !!entity);
});
},
- enabled: enabled(),
- placeholderData: (p) => p,
+ enabled: enabled,
+ placeholderData: keepPreviousData,
meta: { normalize: false },
- }));
-};
-
-type SearchChannelQueryArgs = {
- params: {
- cursor?: string | null;
- page_size?: number;
- };
- body: ChannelSearchRequest;
-};
+ });
+}
-/**
- * Hits the channel-only `/search/channel` endpoint. Use this for the in-channel
- * find-bar so we can pass `sort: 'thread'` (PR #3150) — unified search doesn't
- * accept that field. Response transforms identical to the unified path's
- * `channel` case via the shared `mapChannelSearchResultItem` helper.
- */
-export const useSearchChannelQuery = (
- args: Accessor<SearchChannelQueryArgs>,
+export const useSearchSoupQuery = (
+ args: Accessor<SearchSoupQueryArgs>,
options?: Accessor<SearchQueryOptions>
) => {
- const channelsContext = useChannelsContext();
- const channels = channelsContext.channels;
-
- const pageSize = createMemo(() => args().params.page_size);
-
const request = createMemo(() => {
const body = args().body;
return {
@@ -130,24 +96,51 @@ export const useSearchChannelQuery = (
});
const validSearch = createMemo(() => {
- const q = request().query;
- return !!q && validateSearchServiceText(q);
+ return validateSearchServiceText(request().query);
});
const enabled = createMemo(() => {
if (options?.().enabled === false) return false;
+
return ENABLE_SEARCH_SERVICE && validSearch();
});
- return useInfiniteQuery(() => ({
- queryKey: ['search-channel', args().params, request()] as const,
+ const { channels } = useChannelsContext();
+ const channelNames = createMemo(() =>
+ channels().map(({ id, name }) => ({ id, name }))
+ );
+
+ return useInfiniteQuery(() =>
+ searchSoupQueryOptions(
+ { params: args().params, body: request() },
+ channelNames(),
+ enabled()
+ )
+ );
+};
+
+type SearchChannelQueryArgs = {
+ params: {
+ cursor?: string | null;
+ page_size?: number;
+ };
+ body: ChannelSearchRequest;
+};
+
+function searchChannelQueryOptions(
+ args: SearchChannelQueryArgs,
+ channels: ReadonlyArray<{ id: string; name?: string | null }>,
+ enabled: boolean
+) {
+ return infiniteQueryOptions({
+ queryKey: ['search-channel', args.params, args.body] as const,
queryFn: async (ctx) => {
return throwOnErr(
async () =>
await searchClient.searchChannel(
{
params: ctx.pageParam,
- request: { ...request() },
+ request: { ...args.body },
},
{ signal: ctx.signal }
)
@@ -155,27 +148,70 @@ export const useSearchChannelQuery = (
},
initialPageParam: {
cursor: null as string | null,
- page_size: pageSize(),
+ page_size: args.params.page_size,
},
getNextPageParam: (lastPage) => {
if (!lastPage.next_cursor) return;
return {
cursor: lastPage.next_cursor,
- page_size: pageSize(),
+ page_size: args.params.page_size,
};
},
select: (data) => {
const items = data.pages.flatMap((page) =>
page.results.flatMap((item) =>
- mapChannelSearchResultItem(item, channels())
+ mapChannelSearchResultItem(item, channels)
)
) as WithSearch<ChannelMessageEntity>[];
// stable per query so first page is enough
const totalCount = data.pages[0]?.total_count;
return { items, totalCount };
},
- enabled: enabled(),
- placeholderData: (p) => p,
+ enabled: enabled,
+ placeholderData: keepPreviousData,
meta: { normalize: false },
- }));
+ });
+}
+
+/**
+ * Hits the channel-only `/search/channel` endpoint. Use this for the in-channel
+ * find-bar so we can pass `sort: 'thread'` (PR #3150) — unified search doesn't
+ * accept that field. Response transforms identical to the unified path's
+ * `channel` case via the shared `mapChannelSearchResultItem` helper.
+ */
+export const useSearchChannelQuery = (
+ args: Accessor<SearchChannelQueryArgs>,
+ options?: Accessor<SearchQueryOptions>
+) => {
+ const channelsContext = useChannelsContext();
+ const channels = channelsContext.channels;
+
+ const request = createMemo(() => {
+ const body = args().body;
+ return {
+ ...body,
+ query: body.query?.trim(),
+ };
+ });
+
+ const validSearch = createMemo(() => {
+ const q = request().query;
+ return !!q && validateSearchServiceText(q);
+ });
+
+ const enabled = createMemo(() => {
+ if (options?.().enabled === false) return false;
+ return ENABLE_SEARCH_SERVICE && validSearch();
+ });
+
+ const channelNames = createMemo(() =>
+ channels().map(({ id, name }) => ({ id, name }))
+ );
+ return useInfiniteQuery(() =>
+ searchChannelQueryOptions(
+ { params: args().params, body: request() },
+ channelNames(),
+ enabled()
+ )
+ );
};
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 34731acf26..5366db3c69 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -325,9 +325,14 @@ const formatDisplayName = (text: string, fileType?: string | null) =>
formatDocumentName(text, fileType, { fullyQualifiedBlockName: true });
export const useSearchResponseItemMapper = () => {
- const channelsContext = useChannelsContext();
- const channels = channelsContext.channels;
+ const { channels } = useChannelsContext();
+ return (result: UnifiedSearchResponseItem, searchQuery: string) =>
+ createSearchResponseItemMapper(channels())(result, searchQuery);
+};
+export const createSearchResponseItemMapper = (
+ channels: ReadonlyArray<{ id: string; name?: string | null }>
+) => {
return (
result: UnifiedSearchResponseItem,
searchQuery: string
@@ -500,8 +505,7 @@ export const useSearchResponseItemMapper = () => {
source: 'service',
};
const channelName =
- channels().find((channel) => channel.id === result.channel_id)
- ?.name ??
+ channels.find((channel) => channel.id === result.channel_id)?.name ??
(search.nameHighlight
? extractSearchSnippet(search.nameHighlight)
: blockNameToDefaultFile('channel'));
@@ -522,7 +526,7 @@ export const useSearchResponseItemMapper = () => {
}
case 'channelMessage': {
const channelName =
- channels().find((c) => c.id === result.channel_id)?.name ??
+ channels.find((c) => c.id === result.channel_id)?.name ??
blockNameToDefaultFile('channel');
const search = getSearchData({ type: 'channel', results: [result] });
const content = search.contentHitData?.[0]?.content ?? '';
@@ -624,7 +628,7 @@ export const useSearchResponseItemMapper = () => {
const channelName: string | undefined =
result.metadata.channel_name ??
- channels().find((c) => c.id === result.channel_id)?.name ??
+ channels.find((c) => c.id === result.channel_id)?.name ??
undefined;
const status = result.metadata.status;
@@ -1051,7 +1055,10 @@ const toCalendarEventTime = (
export const isInstructionsMdDoc = (
item: SoupApiItem,
- instructionsIdQuery: UseQueryResult<string | null | undefined, Error>
+ instructionsIdQuery: Pick<
+ UseQueryResult<string | null | undefined, Error>,
+ 'isSuccess' | 'data'
+ >
) => {
if (item.tag !== 'document') return false;
@@ -1063,7 +1070,10 @@ export const isInstructionsMdDoc = (
export const mapSoupPageToEntityList: (
data: SoupPage,
options: {
- instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;
+ instructionsIdQuery: Pick<
+ UseQueryResult<string | null | undefined, Error>,
+ 'isSuccess' | 'data'
+ >;
showSupportedForeignEntities?: boolean;
}
) => SoupEntity[] = (data, options) => {
diff --git a/apps/web/src/lib/queries/storage/attachment-references.ts b/apps/web/src/lib/queries/storage/attachment-references.ts
index a050c7dd92..9e63df65e9 100644
--- a/apps/web/src/lib/queries/storage/attachment-references.ts
+++ b/apps/web/src/lib/queries/storage/attachment-references.ts
@@ -25,28 +25,31 @@ async function fetchAttachmentReferences(
return response.references;
}
+// Cached callbacks outlive the caller; only plain values enter here.
+function attachmentReferencesQueryOptions(
+ type: ItemType,
+ id: string | null | undefined
+) {
+ return {
+ queryKey: id
+ ? attachmentReferencesKeys.list(type, id).queryKey
+ : attachmentReferencesKeys.list._def,
+ queryFn: () => {
+ if (!id) {
+ throw new Error('Entity ID is required to fetch attachment references');
+ }
+ return fetchAttachmentReferences(type, id);
+ },
+ staleTime: ATTACHMENT_REFERENCES_STALE_TIME,
+ enabled: !!id,
+ };
+}
+
export function useAttachmentReferencesQuery(
entityId: Accessor<string | null | undefined>,
entityType: Accessor<ItemType>
) {
- return useQuery(() => {
- const id = entityId();
- const type = entityType();
-
- return {
- queryKey: id
- ? attachmentReferencesKeys.list(type, id).queryKey
- : attachmentReferencesKeys.list._def,
- queryFn: () => {
- if (!id) {
- throw new Error(
- 'Entity ID is required to fetch attachment references'
- );
- }
- return fetchAttachmentReferences(type, id);
- },
- staleTime: ATTACHMENT_REFERENCES_STALE_TIME,
- enabled: !!id,
- };
- });
+ return useQuery(() =>
+ attachmentReferencesQueryOptions(entityType(), entityId())
+ );
}
diff --git a/apps/web/src/lib/queries/storage/deleted.ts b/apps/web/src/lib/queries/storage/deleted.ts
index 0a6f42a21a..853358fb4c 100644
--- a/apps/web/src/lib/queries/storage/deleted.ts
+++ b/apps/web/src/lib/queries/storage/deleted.ts
@@ -3,7 +3,7 @@ import { itemToSafeName } from '@core/constant/allBlocks';
import { storageServiceClient } from '@service-storage/client';
import type { Item } from '@service-storage/generated/schemas/item';
-import { useQuery } from '@tanstack/solid-query';
+import { keepPreviousData, useQuery } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { storageKeys } from './keys';
@@ -35,23 +35,30 @@ function transformItems(items: Item[]): Item[] {
return items.map((item) => ({ ...item, name: itemToSafeName(item) }));
}
+// Cached selectors outlive the caller; keep them at module scope.
+function selectDeletedItems(data: DeletedItemsQueryResponse): Item[] {
+ return transformItems(data.items);
+}
+
function _useDeletedItemsQuery() {
return useQuery(() => ({
...deletedItemsQueryOptions(),
- placeholderData: (prev) => prev,
- select: (data: DeletedItemsQueryResponse): Item[] =>
- transformItems(data.items),
+ placeholderData: keepPreviousData,
+ select: selectDeletedItems,
}));
}
type FileTree = ReturnType<typeof buildFileTree>;
+function selectDeletedTree(data: DeletedItemsQueryResponse): FileTree {
+ return buildFileTree(transformItems(data.items));
+}
+
function _useDeletedTreeQuery() {
return useQuery(() => ({
...deletedItemsQueryOptions(),
- placeholderData: (prev) => prev,
- select: (data: DeletedItemsQueryResponse): FileTree =>
- buildFileTree(transformItems(data.items)),
+ placeholderData: keepPreviousData,
+ select: selectDeletedTree,
}));
}
diff --git a/apps/web/src/lib/queries/storage/document-metadata.ts b/apps/web/src/lib/queries/storage/document-metadata.ts
index 091916d098..14e3f00b62 100644
--- a/apps/web/src/lib/queries/storage/document-metadata.ts
+++ b/apps/web/src/lib/queries/storage/document-metadata.ts
@@ -1,7 +1,7 @@
import { storageServiceClient } from '@service-storage/client';
import type { DocumentMetadata } from '@service-storage/generated/schemas';
import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
-import { useQueries, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQueries, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { entityKeys } from './keys';
@@ -28,14 +28,18 @@ async function fetchDocumentAccessLevel(
return result.value.userAccessLevel;
}
-export function useDocumentMetadataQuery(documentId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: entityKeys.documentMetadata(documentId()).queryKey,
- queryFn: () => fetchDocumentMetadata(documentId()),
+function documentMetadataQueryOptions(documentId: string) {
+ return queryOptions({
+ queryKey: entityKeys.documentMetadata(documentId).queryKey,
+ queryFn: () => fetchDocumentMetadata(documentId),
staleTime: STALE_TIME,
gcTime: GC_TIME,
- enabled: !!documentId(),
- }));
+ enabled: !!documentId,
+ });
+}
+
+export function useDocumentMetadataQuery(documentId: Accessor<string>) {
+ return useQuery(() => documentMetadataQueryOptions(documentId()));
}
/** Shared options keep single-document and collection access checks on the same cache key. */
@@ -49,6 +53,13 @@ export function documentAccessLevelQueryOptions(documentId: string) {
};
}
+function documentAccessLevelEntryQueryOptions(documentId: string) {
+ return {
+ ...documentAccessLevelQueryOptions(documentId),
+ select: (accessLevel: AccessLevel) => ({ documentId, accessLevel }),
+ };
+}
+
/** Loads the current user's access level for a document. */
export function useDocumentAccessLevelQuery(documentId: Accessor<string>) {
return useQuery(() => documentAccessLevelQueryOptions(documentId()));
@@ -62,10 +73,9 @@ export function useDocumentAccessLevelsQuery(
const uniqueDocumentIds = [...new Set(documentIds())];
return {
- queries: uniqueDocumentIds.map((documentId) => ({
- ...documentAccessLevelQueryOptions(documentId),
- select: (accessLevel: AccessLevel) => ({ documentId, accessLevel }),
- })),
+ queries: uniqueDocumentIds.map((documentId) =>
+ documentAccessLevelEntryQueryOptions(documentId)
+ ),
};
});
}
diff --git a/apps/web/src/lib/queries/storage/github-pull-requests.test.ts b/apps/web/src/lib/queries/storage/github-pull-requests.test.ts
index d000160ac4..058df050ff 100644
--- a/apps/web/src/lib/queries/storage/github-pull-requests.test.ts
+++ b/apps/web/src/lib/queries/storage/github-pull-requests.test.ts
@@ -21,7 +21,13 @@ vi.mock('@service-storage/client', () => ({
import type { ResultError } from '@core/util/result';
import type { EnrichedGithubPullRequest } from '@service-auth/generated/schemas';
import type { GithubPullRequest } from '@service-storage/generated/schemas';
-import { fetchDocumentGithubPullRequests } from './github-pull-requests';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createRoot } from 'solid-js';
+import {
+ fetchDocumentGithubPullRequests,
+ useRefreshGithubPullRequest,
+} from './github-pull-requests';
+import { githubPullRequestRefreshKeys } from './keys';
const rawPullRequest: GithubPullRequest = {
displayName: 'macro/macro#42',
@@ -230,3 +236,76 @@ describe('fetchDocumentGithubPullRequests', () => {
});
});
});
+
+describe('useRefreshGithubPullRequest', () => {
+ const refreshedKeys = [
+ ['pr-foreign-entity', 'foreign-entity-1'],
+ ['summary'],
+ ];
+
+ function mountRefresh(client: QueryClient) {
+ return createRoot((dispose) => {
+ QueryClientProvider({
+ client,
+ get children() {
+ useRefreshGithubPullRequest(
+ () => rawPullRequest,
+ () => refreshedKeys
+ );
+ return null;
+ },
+ });
+ return dispose;
+ });
+ }
+
+ it('invalidates the refreshed keys after a successful refresh', async () => {
+ mocks.enrichGithubPullRequests.mockResolvedValue(resultOk([]));
+ const client = new QueryClient();
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const dispose = mountRefresh(client);
+
+ await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: refreshedKeys[0] });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: refreshedKeys[1] });
+ dispose();
+ });
+
+ it('still invalidates when the refresh finishes after unmount', async () => {
+ let resolveEnrichment: (value: unknown) => void = () => {};
+ mocks.enrichGithubPullRequests.mockReturnValue(
+ new Promise((resolve) => {
+ resolveEnrichment = resolve;
+ })
+ );
+ const client = new QueryClient();
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const dispose = mountRefresh(client);
+
+ await vi.waitFor(() =>
+ expect(mocks.enrichGithubPullRequests).toHaveBeenCalledTimes(1)
+ );
+ dispose();
+ resolveEnrichment(resultOk([]));
+
+ await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: refreshedKeys[0] });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: refreshedKeys[1] });
+ });
+
+ it('leaves the stored copy alone when the refresh fails', async () => {
+ mocks.enrichGithubPullRequests.mockResolvedValue(
+ resultErr([createError('UNAUTHORIZED')])
+ );
+ const client = new QueryClient();
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const dispose = mountRefresh(client);
+
+ const refreshKey = githubPullRequestRefreshKeys.refresh(
+ rawPullRequest.githubKey
+ ).queryKey;
+ await vi.waitFor(() => expect(client.getQueryData(refreshKey)).toBe(false));
+ expect(invalidate).not.toHaveBeenCalled();
+ dispose();
+ });
+});
diff --git a/apps/web/src/lib/queries/storage/github-pull-requests.ts b/apps/web/src/lib/queries/storage/github-pull-requests.ts
index f94979309d..eb351f2b8c 100644
--- a/apps/web/src/lib/queries/storage/github-pull-requests.ts
+++ b/apps/web/src/lib/queries/storage/github-pull-requests.ts
@@ -10,7 +10,11 @@ import type {
GithubPullRequest,
GithubPullRequestsResponse,
} from '@service-storage/generated/schemas';
-import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import {
+ type QueryFunctionContext,
+ type QueryKey,
+ useQuery,
+} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import {
documentGithubPullRequestsKeys,
@@ -161,66 +165,83 @@ export async function fetchDocumentGithubPullRequests(
return mergedResponse;
}
+// Cached callbacks outlive the caller; only the resolved id enters them.
+function documentGithubPullRequestsQueryOptions(
+ documentId: string | null | undefined,
+ enabled: boolean
+) {
+ const queryKey = documentId
+ ? documentGithubPullRequestsKeys.list(documentId).queryKey
+ : documentGithubPullRequestsKeys.list._def;
+
+ return {
+ queryKey,
+ queryFn: ({ client }: QueryFunctionContext) => {
+ if (!documentId) {
+ throw new Error(
+ 'Document ID is required to fetch GitHub pull requests'
+ );
+ }
+ return fetchDocumentGithubPullRequests(documentId, {
+ onInitialResponse: (initialResponse) => {
+ client.setQueryData(queryKey, initialResponse);
+ },
+ });
+ },
+ staleTime: DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME,
+ enabled: !!documentId && enabled,
+ };
+}
+
export function useDocumentGithubPullRequestsQuery(
documentId: DocumentIdInput,
enabled?: EnabledInput
) {
- const queryClient = useQueryClient();
-
- return useQuery(() => {
- const currentDocumentId = readDocumentId(documentId);
- const currentEnabled = !!currentDocumentId && readEnabled(enabled);
- const queryKey = currentDocumentId
- ? documentGithubPullRequestsKeys.list(currentDocumentId).queryKey
- : documentGithubPullRequestsKeys.list._def;
-
- return {
- queryKey,
- queryFn: () => {
- if (!currentDocumentId) {
- throw new Error(
- 'Document ID is required to fetch GitHub pull requests'
- );
- }
- return fetchDocumentGithubPullRequests(currentDocumentId, {
- onInitialResponse: (initialResponse) => {
- queryClient.setQueryData(queryKey, initialResponse);
- },
- });
- },
- staleTime: DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME,
- enabled: currentEnabled,
- };
- });
+ return useQuery(() =>
+ documentGithubPullRequestsQueryOptions(
+ readDocumentId(documentId),
+ readEnabled(enabled)
+ )
+ );
+}
+
+// Cached callbacks outlive the caller, so the refresh takes the reference and
+// the keys to invalidate as plain values, never the caller's closures.
+function githubPullRequestRefreshQueryOptions(
+ reference: GithubPullRequestRef | undefined,
+ refreshedKeys: readonly QueryKey[]
+) {
+ return {
+ queryKey: githubPullRequestRefreshKeys.refresh(reference?.githubKey ?? '')
+ .queryKey,
+ enabled: reference !== undefined,
+ queryFn: async ({ client }: QueryFunctionContext) => {
+ const result = await authServiceClient.enrichGithubPullRequests({
+ pullRequests: [reference!],
+ });
+ if (result.isErr()) return false;
+ for (const queryKey of refreshedKeys) {
+ void client.invalidateQueries({ queryKey });
+ }
+ return true;
+ },
+ staleTime: GITHUB_PULL_REQUEST_REFRESH_STALE_TIME,
+ retry: false,
+ refetchOnWindowFocus: false,
+ };
}
/**
* Refresh one pull request from GitHub with the viewer's linked account, which
- * rewrites every stored copy, then run `onRefreshed` so readers of the stored
- * copy load it again. Without a linked account, or when GitHub is unavailable,
- * the stored copy stays as it is.
+ * rewrites every stored copy, then invalidate `refreshedKeys` so readers of the
+ * stored copy load it again. Without a linked account, or when GitHub is
+ * unavailable, the stored copy stays as it is.
*/
export function useRefreshGithubPullRequest(
pullRequest: Accessor<GithubPullRequestRef | undefined>,
- onRefreshed: () => void
+ refreshedKeys: Accessor<readonly QueryKey[]>
) {
- return useQuery(() => {
- const reference = pullRequest();
- return {
- queryKey: githubPullRequestRefreshKeys.refresh(reference?.githubKey ?? '')
- .queryKey,
- enabled: reference !== undefined,
- queryFn: async () => {
- const result = await authServiceClient.enrichGithubPullRequests({
- pullRequests: [reference!],
- });
- if (result.isErr()) return false;
- onRefreshed();
- return true;
- },
- staleTime: GITHUB_PULL_REQUEST_REFRESH_STALE_TIME,
- retry: false,
- refetchOnWindowFocus: false,
- };
- });
+ return useQuery(() =>
+ githubPullRequestRefreshQueryOptions(pullRequest(), refreshedKeys())
+ );
}
diff --git a/apps/web/src/lib/queries/storage/instructions-md.ts b/apps/web/src/lib/queries/storage/instructions-md.ts
index 767545df9b..747606fe15 100644
--- a/apps/web/src/lib/queries/storage/instructions-md.ts
+++ b/apps/web/src/lib/queries/storage/instructions-md.ts
@@ -75,25 +75,32 @@ const getInstructionsMdText = async (id: string | null | undefined) => {
return plaintext;
};
+// Cached callbacks outlive the caller; only the resolved id enters them.
+function instructionsMdTextQueryOptions(
+ id: string | null | undefined,
+ enabled: boolean
+) {
+ return {
+ // Use a placeholder key when id is null/undefined - query is disabled anyway
+ queryKey: id
+ ? instructionsMdKeys.text(id).queryKey
+ : ['instructionsMd', 'text', null],
+ queryFn: () => getInstructionsMdText(id),
+ enabled: enabled && !!id,
+ staleTime: Infinity,
+ throwOnError: false,
+ retry: false,
+ retryOnMount: false,
+ };
+}
+
/** useQuery hook for retrieving the instructions md document text content */
export function useInstructionsMdTextQuery() {
const idQuery = useInstructionsMdIdQuery();
- return useQuery(() => {
- const id = idQuery.data;
- return {
- // Use a placeholder key when id is null/undefined - query is disabled anyway
- queryKey: id
- ? instructionsMdKeys.text(id).queryKey
- : ['instructionsMd', 'text', null],
- queryFn: () => getInstructionsMdText(id),
- enabled: idQuery.isSuccess && !!id,
- staleTime: Infinity,
- throwOnError: false,
- retry: false,
- retryOnMount: false,
- };
- });
+ return useQuery(() =>
+ instructionsMdTextQueryOptions(idQuery.data, idQuery.isSuccess)
+ );
}
/** Creates the instructions md document. Backend prevents duplicates */
diff --git a/apps/web/src/lib/queries/storage/project-data.ts b/apps/web/src/lib/queries/storage/project-data.ts
index 698eb14468..f8141e4724 100644
--- a/apps/web/src/lib/queries/storage/project-data.ts
+++ b/apps/web/src/lib/queries/storage/project-data.ts
@@ -17,19 +17,21 @@ async function fetchProjectData(projectId: string): Promise<Project> {
return result.value.projectMetadata;
}
+// Cached callbacks outlive the caller; only the resolved id enters them.
+function projectDataQueryOptions(id: string | undefined | null) {
+ return {
+ queryKey: id
+ ? entityKeys.projectData(id).queryKey
+ : entityKeys.projectData._def,
+ queryFn: () => fetchProjectData(id!),
+ staleTime: STALE_TIME,
+ gcTime: GC_TIME,
+ enabled: !!id,
+ };
+}
+
export function useProjectDataQuery(
projectId: Accessor<string | undefined | null>
) {
- return useQuery(() => {
- const id = projectId();
- return {
- queryKey: id
- ? entityKeys.projectData(id).queryKey
- : entityKeys.projectData._def,
- queryFn: () => fetchProjectData(id!),
- staleTime: STALE_TIME,
- gcTime: GC_TIME,
- enabled: !!id,
- };
- });
+ return useQuery(() => projectDataQueryOptions(projectId()));
}
diff --git a/apps/web/src/lib/queries/storage/projects.ts b/apps/web/src/lib/queries/storage/projects.ts
index e65700f695..1291479859 100644
--- a/apps/web/src/lib/queries/storage/projects.ts
+++ b/apps/web/src/lib/queries/storage/projects.ts
@@ -12,7 +12,7 @@ import { refetchSoupEntity } from '@queries/soup/cache';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { storageServiceClient } from '@service-storage/client';
import type { Project } from '@service-storage/generated/schemas/project';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { keepPreviousData, useMutation, useQuery } from '@tanstack/solid-query';
import { v4 as uuidv4 } from 'uuid';
import { queryClient } from '../client';
import { storageKeys } from './keys';
@@ -60,23 +60,28 @@ function filterByUserId(
return projects.filter((project) => project.userId === userId);
}
-export function useProjectsQuery() {
- const userId = useUserId();
-
- return useQuery(() => ({
+// Cached callbacks outlive the caller; only the resolved user id enters them.
+function projectsListQueryOptions(userId: string | undefined) {
+ return {
...projectsQueryOptions(),
- placeholderData: (prev) => prev,
+ placeholderData: keepPreviousData,
select: (data: ProjectsQueryResponse): Project[] => {
const allProjects = [...data.projects, ...data.pending];
const sorted = sortProjects(allProjects);
if (!ENABLE_PROJECT_SHARING) {
- return filterByUserId(sorted, userId());
+ return filterByUserId(sorted, userId);
}
return sorted;
},
- }));
+ };
+}
+
+export function useProjectsQuery() {
+ const userId = useUserId();
+
+ return useQuery(() => projectsListQueryOptions(userId()));
}
export function invalidateProjects() {
diff --git a/apps/web/src/lib/queries/storage/system-skills.ts b/apps/web/src/lib/queries/storage/system-skills.ts
index 1361a48091..2e4f9dc156 100644
--- a/apps/web/src/lib/queries/storage/system-skills.ts
+++ b/apps/web/src/lib/queries/storage/system-skills.ts
@@ -5,6 +5,23 @@ import { createMemo } from 'solid-js';
const SYSTEM_SKILLS_QUERY_KEY = ['storage', 'system-skills'] as const;
+async function fetchSystemSkills() {
+ const result = await storageServiceClient.getSystemSkills();
+ if (result.isErr()) {
+ throw new Error('Failed to fetch system skills');
+ }
+ return result.value.skills;
+}
+
+function systemSkillsQueryOptions() {
+ return {
+ queryKey: SYSTEM_SKILLS_QUERY_KEY,
+ queryFn: fetchSystemSkills,
+ staleTime: Number.POSITIVE_INFINITY,
+ refetchOnWindowFocus: false,
+ };
+}
+
/**
* Built-in system skills served by the storage service. System skills are
* static, code-defined AI instructions (crates/system_skills) with well-known
@@ -14,18 +31,7 @@ const SYSTEM_SKILLS_QUERY_KEY = ['storage', 'system-skills'] as const;
* The list is fixed per deploy, so it is fetched once and cached forever.
*/
export function useSystemSkillsQuery() {
- const query = useQuery(() => ({
- queryKey: SYSTEM_SKILLS_QUERY_KEY,
- queryFn: async () => {
- const result = await storageServiceClient.getSystemSkills();
- if (result.isErr()) {
- throw new Error('Failed to fetch system skills');
- }
- return result.value.skills;
- },
- staleTime: Number.POSITIVE_INFINITY,
- refetchOnWindowFocus: false,
- }));
+ const query = useQuery(() => systemSkillsQueryOptions());
const skills = createMemo<SystemSkillSummary[]>(() =>
query.isSuccess ? (query.data ?? []) : []
diff --git a/apps/web/src/lib/queries/storage/task-duplicates.ts b/apps/web/src/lib/queries/storage/task-duplicates.ts
index 9c1e6880d5..7332af3a58 100644
--- a/apps/web/src/lib/queries/storage/task-duplicates.ts
+++ b/apps/web/src/lib/queries/storage/task-duplicates.ts
@@ -5,7 +5,12 @@ import {
type TaskDuplicate,
type TaskSimilarityResult,
} from '@service-storage/client';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import {
+ keepPreviousData,
+ queryOptions,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { entityKeys, taskSimilaritySearchKeys } from './keys';
@@ -39,13 +44,17 @@ async function fetchTaskDuplicates(
return result.value;
}
-export function useTaskDuplicatesQuery(documentId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: entityKeys.taskDuplicates(documentId()).queryKey,
- queryFn: () => fetchTaskDuplicates(documentId()),
- enabled: !!documentId(),
+function taskDuplicatesQueryOptions(documentId: string) {
+ return queryOptions({
+ queryKey: entityKeys.taskDuplicates(documentId).queryKey,
+ queryFn: () => fetchTaskDuplicates(documentId),
+ enabled: !!documentId,
staleTime: 30 * 1000,
- }));
+ });
+}
+
+export function useTaskDuplicatesQuery(documentId: Accessor<string>) {
+ return useQuery(() => taskDuplicatesQueryOptions(documentId()));
}
export function useDismissTaskDuplicatesMutation(documentId: Accessor<string>) {
@@ -90,6 +99,17 @@ async function searchSimilarTasks(
return result.value;
}
+function taskSimilaritySearchQueryOptions(input: TaskSimilaritySearchInput) {
+ return queryOptions({
+ queryKey: taskSimilaritySearchKeys.forInput(input).queryKey,
+ queryFn: () => searchSimilarTasks(input),
+ // Only query when there is something to search on: a title or a body.
+ enabled: input.title.trim().length > 0 || input.markdown.trim().length > 0,
+ staleTime: 30 * 1000,
+ placeholderData: keepPreviousData,
+ });
+}
+
/**
* Live, ephemeral similarity search used by the task composer. Hits the
* stateless `/documents/similarity_search` HTTP endpoint — nothing is
@@ -98,15 +118,7 @@ async function searchSimilarTasks(
export function useTaskSimilaritySearchQuery(
input: Accessor<TaskSimilaritySearchInput>
) {
- return useQuery(() => ({
- queryKey: taskSimilaritySearchKeys.forInput(input()).queryKey,
- queryFn: () => searchSimilarTasks(input()),
- // Only query when there is something to search on: a title or a body.
- enabled:
- input().title.trim().length > 0 || input().markdown.trim().length > 0,
- staleTime: 30 * 1000,
- placeholderData: (prev) => prev,
- }));
+ return useQuery(() => taskSimilaritySearchQueryOptions(input()));
}
export function useDeleteThisDuplicateTaskMutation(
diff --git a/apps/web/src/lib/queries/storage/team-share.ts b/apps/web/src/lib/queries/storage/team-share.ts
index 9c96909091..41c3848fce 100644
--- a/apps/web/src/lib/queries/storage/team-share.ts
+++ b/apps/web/src/lib/queries/storage/team-share.ts
@@ -2,29 +2,33 @@ import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { DocumentTeamShareResponse } from '@service-storage/generated/schemas/documentTeamShareResponse';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { entityKeys } from './keys';
const STALE_TIME = 60 * 1000;
-/**
- * Team-share state of a document, resolved against the owner's team.
- * `teamId` is absent when the owner does not belong to a team — the
- * "Share with team" toggle should be hidden in that case.
- */
-export function useDocumentTeamShareQuery(documentId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: entityKeys.documentTeamShare(documentId()).queryKey,
+function documentTeamShareQueryOptions(documentId: string) {
+ return queryOptions({
+ queryKey: entityKeys.documentTeamShare(documentId).queryKey,
queryFn: () =>
throwOnErr(() =>
storageServiceClient.getDocumentTeamShare({
- documentId: documentId(),
+ documentId,
})
),
staleTime: STALE_TIME,
- enabled: !!documentId(),
- }));
+ enabled: !!documentId,
+ });
+}
+
+/**
+ * Team-share state of a document, resolved against the owner's team.
+ * `teamId` is absent when the owner does not belong to a team — the
+ * "Share with team" toggle should be hidden in that case.
+ */
+export function useDocumentTeamShareQuery(documentId: Accessor<string>) {
+ return useQuery(() => documentTeamShareQueryOptions(documentId()));
}
/** Share or unshare a document with the owner's team (grants the team Edit). */
diff --git a/apps/web/src/lib/queries/storage/team-task.ts b/apps/web/src/lib/queries/storage/team-task.ts
index 63de995f0f..50fd469d6c 100644
--- a/apps/web/src/lib/queries/storage/team-task.ts
+++ b/apps/web/src/lib/queries/storage/team-task.ts
@@ -4,32 +4,30 @@ import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { teamTaskKeys } from './keys';
-/** Resolves a stable team-task slug to its canonical document. */
-export function useTeamTaskQuery(slug: Accessor<string | undefined>) {
- return useQuery(() => {
- const currentSlug = slug();
+// Cached callbacks outlive the caller; only the resolved slug enters them.
+function teamTaskQueryOptions(slug: string | undefined) {
+ return {
+ queryKey: slug
+ ? teamTaskKeys.bySlug(slug).queryKey
+ : teamTaskKeys.bySlug._def,
+ queryFn: ({ signal }: { signal: AbortSignal }) => {
+ if (!slug) {
+ throw new Error('A team-task slug is required');
+ }
- return {
- queryKey: currentSlug
- ? teamTaskKeys.bySlug(currentSlug).queryKey
- : teamTaskKeys.bySlug._def,
- queryFn: ({ signal }: { signal: AbortSignal }) => {
- if (!currentSlug) {
- throw new Error('A team-task slug is required');
- }
+ // DSS resolves the slug against the authenticated user's team.
+ return throwOnErr(() =>
+ storageServiceClient.getDocumentByTeamSlug({ slug, signal })
+ );
+ },
+ // Resolution failures are deterministic (404/403), so an automatic
+ // retry only delays the not-found state; the route offers manual retry.
+ retry: false,
+ enabled: !!slug,
+ };
+}
- // DSS resolves the slug against the authenticated user's team.
- return throwOnErr(() =>
- storageServiceClient.getDocumentByTeamSlug({
- slug: currentSlug,
- signal,
- })
- );
- },
- // Resolution failures are deterministic (404/403), so an automatic
- // retry only delays the not-found state; the route offers manual retry.
- retry: false,
- enabled: !!currentSlug,
- };
- });
+/** Resolves a stable team-task slug to its canonical document. */
+export function useTeamTaskQuery(slug: Accessor<string | undefined>) {
+ return useQuery(() => teamTaskQueryOptions(slug()));
}
diff --git a/apps/web/src/lib/queries/sync/document-peers.ts b/apps/web/src/lib/queries/sync/document-peers.ts
index 156b2cafb3..7953bee2af 100644
--- a/apps/web/src/lib/queries/sync/document-peers.ts
+++ b/apps/web/src/lib/queries/sync/document-peers.ts
@@ -1,6 +1,6 @@
import { ThrownResultError } from '@core/util/result';
import { syncServiceClient } from '@service-sync/client';
-import { useQuery } from '@tanstack/solid-query';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { syncKeys } from './keys';
@@ -12,12 +12,16 @@ async function fetchDocumentPeers(
return new Map(result.value.peers.map((p) => [String(p.peer_id), p.user_id]));
}
-export function useDocumentPeersQuery(documentId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: syncKeys.documentPeers(documentId()).queryKey,
- queryFn: () => fetchDocumentPeers(documentId()),
+function documentPeersQueryOptions(documentId: string) {
+ return queryOptions({
+ queryKey: syncKeys.documentPeers(documentId).queryKey,
+ queryFn: () => fetchDocumentPeers(documentId),
staleTime: 60 * 1000,
gcTime: 10 * 60 * 1000,
- enabled: !!documentId(),
- }));
+ enabled: !!documentId,
+ });
+}
+
+export function useDocumentPeersQuery(documentId: Accessor<string>) {
+ return useQuery(() => documentPeersQueryOptions(documentId()));
}
diff --git a/apps/web/src/lib/queries/team/invitations.ts b/apps/web/src/lib/queries/team/invitations.ts
index 19337e43f3..4f26f6abd3 100644
--- a/apps/web/src/lib/queries/team/invitations.ts
+++ b/apps/web/src/lib/queries/team/invitations.ts
@@ -10,11 +10,14 @@ import { type MutationCallbacks, withCallbacks } from '../utils';
import { teamKeys } from './keys';
import { invalidateUserTeams } from './teams';
+function fetchUserInvites() {
+ return throwOnErr(() => authServiceClient.getUserInvites());
+}
+
export function useUserInvitesQuery() {
return useQuery(() => ({
queryKey: teamKeys.userInvites.queryKey,
- queryFn: async () =>
- await throwOnErr(() => authServiceClient.getUserInvites()),
+ queryFn: fetchUserInvites,
}));
}
diff --git a/apps/web/src/lib/queries/team/invites.ts b/apps/web/src/lib/queries/team/invites.ts
index 932ffacaae..ca0dcf0dc3 100644
--- a/apps/web/src/lib/queries/team/invites.ts
+++ b/apps/web/src/lib/queries/team/invites.ts
@@ -11,11 +11,14 @@ import { type MutationCallbacks, withCallbacks } from '../utils';
import { teamKeys } from './keys';
+function fetchTeamInvites() {
+ return throwOnErr(() => authServiceClient.getTeamInvites());
+}
+
export function useTeamInvitesQuery(teamId: Accessor<string>) {
return useQuery(() => ({
queryKey: teamKeys.invites(teamId()).queryKey,
- queryFn: async () =>
- await throwOnErr(() => authServiceClient.getTeamInvites()),
+ queryFn: fetchTeamInvites,
enabled: !!teamId(),
}));
}
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index db45acb9bf..af98e25b11 100644
--- a/apps/web/src/lib/queries/team/teams.ts
+++ b/apps/web/src/lib/queries/team/teams.ts
@@ -22,18 +22,25 @@ import { type MutationCallbacks, withCallbacks } from '../utils';
import { teamKeys } from './keys';
+function fetchUserTeams() {
+ return throwOnErr(() => authServiceClient.getUserTeams());
+}
+
+function fetchTeam() {
+ return throwOnErr(() => authServiceClient.getTeam());
+}
+
export function useUserTeamsQuery() {
return useQuery(() => ({
queryKey: teamKeys.userTeams.queryKey,
- queryFn: async () =>
- await throwOnErr(() => authServiceClient.getUserTeams()),
+ queryFn: fetchUserTeams,
}));
}
export function useTeamQuery(teamId: Accessor<string>) {
return useQuery(() => ({
queryKey: teamKeys.detail(teamId()).queryKey,
- queryFn: async () => await throwOnErr(() => authServiceClient.getTeam()),
+ queryFn: fetchTeam,
enabled: !!teamId(),
}));
}
@@ -42,7 +49,7 @@ export function useTeamQuery(teamId: Accessor<string>) {
export function useCurrentTeamQuery(enabled?: Accessor<boolean>) {
return useQuery(() => ({
queryKey: teamKeys.currentTeam.queryKey,
- queryFn: async () => await throwOnErr(() => authServiceClient.getTeam()),
+ queryFn: fetchTeam,
enabled: enabled?.() ?? true,
}));
}
diff --git a/apps/web/src/lib/queries/user-api-keys/user-api-keys.ts b/apps/web/src/lib/queries/user-api-keys/user-api-keys.ts
index 296c014dc2..64d4a6be05 100644
--- a/apps/web/src/lib/queries/user-api-keys/user-api-keys.ts
+++ b/apps/web/src/lib/queries/user-api-keys/user-api-keys.ts
@@ -7,11 +7,14 @@ import { useMutation, useQuery } from '@tanstack/solid-query';
import { userApiKeyKeys } from './keys';
import { normalizeUserApiKeyName } from './name';
+function fetchUserApiKeys(): Promise<UserApiKeyInfo[]> {
+ return throwOnErr(() => storageServiceClient.listUserApiKeys());
+}
+
export function useUserApiKeysQuery() {
return useQuery(() => ({
queryKey: userApiKeyKeys.list.queryKey,
- queryFn: async (): Promise<UserApiKeyInfo[]> =>
- await throwOnErr(() => storageServiceClient.listUserApiKeys()),
+ queryFn: fetchUserApiKeys,
}));
}