Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

refactor: standardize resource ID handling and improve flow file management

Dmitry Ngba14913c0e2d
diff --git a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
index 66bb4482..b85979f2 100644
--- a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
+++ b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
@@ -1,7 +1,7 @@
import { FolderInput, Loader2, Search, X } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
-import { dedupeOverlappingPaths, FileManager, type FileNode } from '@/components/file-manager';
+import { FileManager, type FileNode } from '@/components/file-manager';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
@@ -44,11 +44,14 @@ const FlowFilesAttachResourcesDialogBody = ({
// Map selected paths back to resource ids on submit. Built lazily — the lookup
// is only walked once per attach, so a per-render `Map` allocation is wasteful.
+ // `resource.id` is canonically numeric in the cache (see `resources-rest.ts`)
+ // even though codegen types it as `string`; coerce here so downstream callers
+ // that rely on the `string` contract (`useFlowFilesAttachResources`) stay safe.
const pathToIdRef = useMemo(() => {
const map = new Map<string, string>();
for (const resource of resources) {
- map.set(resource.path, resource.id);
+ map.set(resource.path, String(resource.id));
}
return map;
@@ -63,11 +66,16 @@ const FlowFilesAttachResourcesDialogBody = ({
return;
}
- // Drop descendants of any picked directory so the backend doesn't
- // re-process them — a recursive copy of the parent already covers them.
+ // Forward every explicitly selected path's ID to the backend. Earlier
+ // versions deduped descendants of any picked directory on the assumption
+ // that the backend would copy directory trees recursively — it does not
+ // (`flowfiles.CopyResourcesToFlow` only `MkdirAll`s a directory ref and
+ // file refs are copied individually). Until that becomes recursive on
+ // the backend, the user must multi-select a folder together with its
+ // children to attach the contents.
const ids: string[] = [];
- for (const path of dedupeOverlappingPaths(selectedPaths)) {
+ for (const path of selectedPaths) {
const id = pathToIdRef.get(path);
if (id) {
diff --git a/frontend/src/features/flows/files/flow-files-utils.ts b/frontend/src/features/flows/files/flow-files-utils.ts
index d493976d..09d90afa 100644
--- a/frontend/src/features/flows/files/flow-files-utils.ts
+++ b/frontend/src/features/flows/files/flow-files-utils.ts
@@ -7,21 +7,24 @@ import { CONTAINER_PATH_PREFIX, RESOURCES_PATH_PREFIX, UPLOADS_PATH_PREFIX } fro
export type FlowFile = FlowFileFragmentFragment;
+/**
+ * Wire shape of `models.FlowFile` (REST JSON, snake_case). The internal
+ * `FlowFile` alias mirrors the GraphQL camelCase fragment for use in the
+ * FileManager UI. Current consumers of `FlowFilesResponse` only read
+ * `files.length` and `files[0].name`, so no conversion helper is needed yet.
+ */
export interface FlowFilesResponse {
- files: Array<FlowFile>;
+ files: RestFlowFile[];
total: number;
}
-/** Mirrors `models.ResourceEntry` from the backend (REST shape, not GraphQL). */
-export interface ResourceEntry {
- createdAt: string;
- id: number;
- isDir: boolean;
+export interface RestFlowFile {
+ id: string;
+ is_dir: boolean;
+ modified_at: string;
name: string;
path: string;
size: number;
- updatedAt: string;
- userId: number;
}
const ROOT_PREFIXES = [`${UPLOADS_PATH_PREFIX}/`, `${CONTAINER_PATH_PREFIX}/`, `${RESOURCES_PATH_PREFIX}/`];
diff --git a/frontend/src/features/flows/files/use-flow-files-attach-resources.ts b/frontend/src/features/flows/files/use-flow-files-attach-resources.ts
index fa2993eb..1509306c 100644
--- a/frontend/src/features/flows/files/use-flow-files-attach-resources.ts
+++ b/frontend/src/features/flows/files/use-flow-files-attach-resources.ts
@@ -1,6 +1,7 @@
import { useCallback, useState } from 'react';
import { toast } from 'sonner';
+import { resourceIdsToWire } from '@/features/resources/resources-rest';
import { api, getApiErrorMessage } from '@/lib/axios';
import type { FlowFilesResponse } from './flow-files-utils';
@@ -8,13 +9,19 @@ import type { FlowFilesResponse } from './flow-files-utils';
import { FLOW_FILES_ATTACH_RESOURCES_API_PATH, RESOURCES_TARGET_DIRECTORY } from './flow-files-constants';
interface AttachOptions {
+ /** GraphQL `UserResource.id` values (strings). Converted at the REST boundary. */
ids: string[];
shouldOverwrite: boolean;
}
+/**
+ * Wire shape of `models.AddResourcesRequest`. Backend expects `ids` as
+ * uint64 (JSON numbers); see {@link resourceIdsToWire} for the bridge from
+ * the GraphQL `string` ID convention used internally.
+ */
interface AttachResourcesRequestBody {
force: boolean;
- ids: string[];
+ ids: number[];
}
interface UseFlowFilesAttachResourcesParams {
@@ -46,6 +53,20 @@ export const useFlowFilesAttachResources = ({
return false;
}
+ let numericIds: number[];
+
+ try {
+ numericIds = resourceIdsToWire(ids);
+ } catch (error) {
+ // Non-numeric IDs indicate an upstream cache contract bug, not a user
+ // mistake. Surface a developer-friendly toast and bail out loudly.
+ const description = error instanceof Error ? error.message : 'Invalid resource IDs.';
+
+ toast.error('Attach failed', { description });
+
+ return false;
+ }
+
setIsAttaching(true);
try {
@@ -53,13 +74,13 @@ export const useFlowFilesAttachResources = ({
FLOW_FILES_ATTACH_RESOURCES_API_PATH(flowId),
{
force: shouldOverwrite,
- ids,
+ ids: numericIds,
},
{ timeout: 0 },
);
toast.success('Resources attached', {
- description: `Copied ${ids.length} ${ids.length === 1 ? 'item' : 'items'} to ${RESOURCES_TARGET_DIRECTORY}`,
+ description: `Copied ${numericIds.length} ${numericIds.length === 1 ? 'item' : 'items'} to ${RESOURCES_TARGET_DIRECTORY}`,
});
onSuccess?.();
diff --git a/frontend/src/features/flows/files/use-flow-files-promote.ts b/frontend/src/features/flows/files/use-flow-files-promote.ts
index 6c7b7d0f..bc695900 100644
--- a/frontend/src/features/flows/files/use-flow-files-promote.ts
+++ b/frontend/src/features/flows/files/use-flow-files-promote.ts
@@ -2,9 +2,9 @@ import { useCallback, useState } from 'react';
import { toast } from 'sonner';
import { z } from 'zod';
-import { api, getApiErrorMessage } from '@/lib/axios';
+import type { RestResourceList } from '@/features/resources/resources-rest';
-import type { ResourceEntry } from './flow-files-utils';
+import { api, getApiErrorMessage } from '@/lib/axios';
import { FLOW_FILES_PROMOTE_API_PATH } from './flow-files-constants';
@@ -23,31 +23,35 @@ export type FlowFilesPromoteFormValues = z.infer<typeof flowFilesPromoteFormSche
interface PromoteRequestBody {
destination: string;
force: boolean;
- sourcePath: string;
+ source: string;
}
interface UseFlowFilesPromoteParams {
flowId: null | string;
- onSuccess?: (entry: ResourceEntry) => void;
}
interface UseFlowFilesPromoteResult {
isPromoting: boolean;
- promote: (sourcePath: string, values: FlowFilesPromoteFormValues) => Promise<boolean>;
+ promote: (source: string, values: FlowFilesPromoteFormValues) => Promise<boolean>;
}
const PROMOTE_OVERWRITE_HINT = 'Resource already exists — enable "Overwrite" to replace it';
/**
* Wraps the "promote flow file → user resource" REST call (`POST /files/to-resources`)
- * with toast notifications and a loading flag. Returns a `promote(sourcePath, values)`
+ * with toast notifications and a loading flag. Returns a `promote(source, values)`
* callback that resolves to `true` on success so the dialog can decide whether to close.
+ *
+ * The endpoint accepts both single files and directories — the backend always returns
+ * a `ResourceList` covering every entry it created or updated. The response payload
+ * itself is discarded: the resource library Apollo cache is kept in sync via the
+ * `resourceAdded` / `resourceUpdated` GraphQL subscriptions.
*/
-export const useFlowFilesPromote = ({ flowId, onSuccess }: UseFlowFilesPromoteParams): UseFlowFilesPromoteResult => {
+export const useFlowFilesPromote = ({ flowId }: UseFlowFilesPromoteParams): UseFlowFilesPromoteResult => {
const [isPromoting, setIsPromoting] = useState(false);
const promote = useCallback(
- async (sourcePath: string, { destination, shouldOverwrite }: FlowFilesPromoteFormValues): Promise<boolean> => {
+ async (source: string, { destination, shouldOverwrite }: FlowFilesPromoteFormValues): Promise<boolean> => {
if (!flowId) {
return false;
}
@@ -55,12 +59,12 @@ export const useFlowFilesPromote = ({ flowId, onSuccess }: UseFlowFilesPromotePa
setIsPromoting(true);
try {
- const response = await api.post<ResourceEntry, PromoteRequestBody>(
+ await api.post<RestResourceList, PromoteRequestBody>(
FLOW_FILES_PROMOTE_API_PATH(flowId),
{
destination: destination.trim(),
force: shouldOverwrite,
- sourcePath,
+ source,
},
{ timeout: 0 },
);
@@ -69,10 +73,6 @@ export const useFlowFilesPromote = ({ flowId, onSuccess }: UseFlowFilesPromotePa
description: `Stored at ${destination.trim()} in your resource library`,
});
- if (response.status === 'success' && response.data) {
- onSuccess?.(response.data);
- }
-
return true;
} catch (error) {
const description = getApiErrorMessage(error, 'Failed to save resource', {
@@ -86,7 +86,7 @@ export const useFlowFilesPromote = ({ flowId, onSuccess }: UseFlowFilesPromotePa
setIsPromoting(false);
}
},
- [flowId, onSuccess],
+ [flowId],
);
return {
diff --git a/frontend/src/features/flows/flow-form.tsx b/frontend/src/features/flows/flow-form.tsx
index 11559e31..a8dcbb3e 100644
--- a/frontend/src/features/flows/flow-form.tsx
+++ b/frontend/src/features/flows/flow-form.tsx
@@ -91,8 +91,13 @@ export const FlowForm = ({
const fileInputRef = useRef<HTMLInputElement>(null);
+ // Resources are rendered as a hierarchy: alphabetical sort by full path
+ // produces the right ordering for siblings at every depth (parents before
+ // their descendants, peers in alphabetical order). Each row's nesting level
+ // is then derived from the slash count and rendered as a left indent so the
+ // user can visually trace files into their parent directories.
const sortedResources = useMemo(
- () => [...resources].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
+ () => [...resources].sort((a, b) => a.path.localeCompare(b.path, undefined, { sensitivity: 'base' })),
[resources],
);
@@ -109,6 +114,8 @@ export const FlowForm = ({
);
}, [sortedResources, resourceSearch]);
+ const isResourceSearchActive = resourceSearch.trim().length > 0;
+
const filteredTemplates = useMemo(() => {
if (!templateSearch.trim()) {
return templates;
@@ -159,13 +166,12 @@ export const FlowForm = ({
const resourceIds = useWatch({ control, name: 'resourceIds' });
const updateResourceIds = useCallback(
- (updater: ((current: string[]) => string[]) | string[]) => {
+ (updater: ((current: string[]) => string[]) | Array<number | string>) => {
const current = getValues('resourceIds') ?? [];
const raw = typeof updater === 'function' ? updater(current) : updater;
- // TODO(backend): drop the `String(id)` coercion once the REST `/resources/`
- // endpoints return `id` as a string (matching the GraphQL `ID` scalar). Until
- // then this is a safety net for stray numeric ids that would fail zod's
- // `z.array(z.string())` and silently block submission.
+ // Canonical cache shape carries `id` as a number (see `resources-rest.ts`),
+ // while zod enforces `z.array(z.string())` on the form state. String-coerce
+ // every incoming value so the form always holds a consistent string array.
const next = raw.map((id) => String(id));
setValue('resourceIds', next, { shouldDirty: true, shouldValidate: true });
},
@@ -173,7 +179,7 @@ export const FlowForm = ({
);
const flowResources = useMemo<UserResourceFragmentFragment[]>(() => {
- const byId = new Map(resources.map((item) => [item.id, item]));
+ const byId = new Map(resources.map((item) => [String(item.id), item]));
return resourceIds
.map((id) => byId.get(id))
@@ -182,7 +188,7 @@ export const FlowForm = ({
const upload = useResourcesUpload({
onSuccess: (uploaded) => {
- const ids = uploaded.items.map((item) => item.id);
+ const ids = uploaded.items.map((item) => String(item.id));
if (ids.length === 0) {
return;
@@ -333,11 +339,12 @@ export const FlowForm = ({
>
{flowResources.map((resource) => {
const Icon = resource.isDir ? Folder : FileText;
+ const resourceId = String(resource.id);
return (
<div
className="bg-muted/50 flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-xs"
- key={resource.id}
+ key={resourceId}
title={resource.path}
>
<Icon className="text-muted-foreground size-3.5 shrink-0" />
@@ -348,7 +355,7 @@ export const FlowForm = ({
aria-label={`Remove ${resource.name}`}
className="text-muted-foreground hover:text-destructive ml-0.5 flex shrink-0 items-center justify-center"
disabled={isFormDisabled}
- onClick={() => handleRemoveAttachment(resource.id)}
+ onClick={() => handleRemoveAttachment(resourceId)}
type="button"
>
<X className="size-3.5" />
@@ -640,12 +647,19 @@ export const FlowForm = ({
</DropdownMenuItem>
) : (
filteredResources.map((resource) => {
- const isSelected = resourceIds.includes(resource.id);
+ const resourceId = String(resource.id);
+ const isSelected = resourceIds.includes(resourceId);
const Icon = resource.isDir ? Folder : FileText;
+ // Depth derived from the path's slash count; ignored while a
+ // search query is active so matches don't appear orphaned
+ // beneath hidden ancestors.
+ const depth = isResourceSearchActive
+ ? 0
+ : resource.path.split('/').length - 1;
return (
<DropdownMenuItem
- key={resource.id}
+ key={resourceId}
onSelect={(event) => {
event.preventDefault();
@@ -653,8 +667,9 @@ export const FlowForm = ({
return;
}
- handleToggleAttachment(resource.id);
+ handleToggleAttachment(resourceId);
}}
+ style={{ paddingLeft: `${0.5 + depth * 0.875}rem` }}
>
<div className="flex w-full min-w-0 items-center gap-2">
<Icon className="text-muted-foreground size-4 shrink-0" />
@@ -662,11 +677,12 @@ export const FlowForm = ({
<span className="truncate">
{resource.name}
</span>
- {resource.path !== resource.name && (
- <span className="text-muted-foreground truncate text-xs">
- {resource.path}
- </span>
- )}
+ {isResourceSearchActive &&
+ resource.path !== resource.name && (
+ <span className="text-muted-foreground truncate text-xs">
+ {resource.path}
+ </span>
+ )}
</div>
{isSelected && (
<Check className="ml-auto size-4 shrink-0" />
diff --git a/frontend/src/features/resources/resources-rest.ts b/frontend/src/features/resources/resources-rest.ts
new file mode 100644
index 00000000..f1e393bf
--- /dev/null
+++ b/frontend/src/features/resources/resources-rest.ts
@@ -0,0 +1,99 @@
+import type { UserResourceFragmentFragment } from '@/graphql/types';
+
+/**
+ * Canonicalisation utilities for `UserResource` entries flowing through the
+ * Apollo cache.
+ *
+ * SOURCE OF TRUTH — DB:
+ * `user_resources.id` is `BIGINT` (int64). The Go layer (GORM/REST and
+ * gqlgen) preserves this as `int64` / `uint64`.
+ *
+ * WIRE FORMAT (uniform across both transports in this project):
+ * Both REST JSON (`models.ResourceEntry`) and GraphQL subscription payloads
+ * (gqlgen `ID!` is bound to `graphql.Int64` in `gqlgen.yml`) emit IDs as
+ * JSON **numbers**. The frontend `UserResourceFragmentFragment.id: string`
+ * typing is an unfortunate codegen default for the `ID` scalar — it lies
+ * about the runtime shape until the codegen mapping is fixed (Phase C).
+ *
+ * CANONICAL CACHE SHAPE:
+ * To keep Apollo's normalised store internally consistent with what the
+ * GraphQL subscription auto-writer emits, REST hydration MUST insert the
+ * IDs in the same numeric form. Otherwise array-field dedup that compares
+ * `id` strictly (`===`) would treat `"28"` (REST-coerced) and `28`
+ * (subscription) as different items and append a duplicate ref to the
+ * `resources` query field.
+ *
+ * Downstream consumers that compare cache `id` against form-state strings
+ * (e.g. `FlowForm.resourceIds: z.array(z.string())`) MUST coerce defensively
+ * via `String(resource.id)` at the boundary. These local coercions disappear
+ * once the codegen mapping is updated to `id: number`.
+ */
+
+/** Wire shape of `models.ResourceEntry` (REST JSON, snake_case). */
+export interface RestResourceEntry {
+ created_at: string;
+ id: number;
+ is_dir: boolean;
+ name: string;
+ path: string;
+ size: number;
+ updated_at: string;
+ user_id: number;
+}
+
+/** Wire shape of `models.ResourceList` (REST JSON). */
+export interface RestResourceList {
+ items?: null | RestResourceEntry[];
+ total?: number;
+}
+
+/**
+ * Convert a REST `RestResourceEntry` into the canonical camelCase shape that
+ * Apollo stores under `UserResource:<id>`. Numeric `id` / `user_id` are kept
+ * as `number` (matching gqlgen subscription wire), with a `as unknown as
+ * string` cast to satisfy the codegen `UserResourceFragmentFragment.id:
+ * string` contract until that mapping is corrected upstream.
+ */
+export const restResourceEntryToFragment = (rest: RestResourceEntry): UserResourceFragmentFragment => ({
+ createdAt: rest.created_at,
+ id: rest.id as unknown as string,
+ isDir: rest.is_dir,
+ name: rest.name,
+ path: rest.path,
+ size: rest.size,
+ updatedAt: rest.updated_at,
+ userId: rest.user_id as unknown as string,
+});
+
+/**
+ * Convert a single canonical resource ID (as it lives in the cache) into the
+ * REST numeric wire format. Accepts both the codegen-typed `string` and the
+ * actual runtime `number` that the cache stores, so callers can pass values
+ * read straight from `UserResource.id` without first stringifying them.
+ *
+ * Throws on any value that is not a positive `Number.isSafeInteger`. For
+ * string inputs an additional round-trip check (`String(parsed) === id`)
+ * rejects leading zeros, whitespace, signs and other malformed encodings —
+ * such input would signal a contract violation upstream, not user error.
+ */
+export const resourceIdToWire = (id: number | string): number => {
+ if (typeof id === 'number') {
+ if (!Number.isSafeInteger(id) || id <= 0) {
+ throw new Error(`Invalid resource ID for REST wire: ${JSON.stringify(id)}`);
+ }
+
+ return id;
+ }
+
+ const parsed = Number(id);
+
+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || String(parsed) !== id) {
+ throw new Error(`Invalid resource ID for REST wire: ${JSON.stringify(id)}`);
+ }
+
+ return parsed;
+};
+
+/** Bulk variant of {@link resourceIdToWire}. Throws on the first invalid ID. */
+export const resourceIdsToWire = (ids: ReadonlyArray<number | string>): number[] =>
+ ids.map((id) => resourceIdToWire(id));
diff --git a/frontend/src/features/resources/use-resources-upload.ts b/frontend/src/features/resources/use-resources-upload.ts
index e3a7ec24..bf29e4a3 100644
--- a/frontend/src/features/resources/use-resources-upload.ts
+++ b/frontend/src/features/resources/use-resources-upload.ts
@@ -11,6 +11,7 @@ import {
MAX_UPLOAD_TOTAL_SIZE_MB,
RESOURCES_API_PATH,
} from './resources-constants';
+import { restResourceEntryToFragment, type RestResourceList } from './resources-rest';
import { pluralizeItems } from './resources-utils';
interface UploadOptions {
@@ -121,24 +122,20 @@ export const useResourcesUpload = ({ onSuccess }: UseResourcesUploadParams = {})
setIsUploading(true);
try {
- const response = await api.post<UploadResponse, FormData>(RESOURCES_API_PATH, formData, {
+ const response = await api.post<RestResourceList, FormData>(RESOURCES_API_PATH, formData, {
headers: { 'Content-Type': undefined },
params: options?.dir ? { dir: options.dir } : undefined,
timeout: 0,
});
+ // Backend sends `models.ResourceList` (snake_case, numeric IDs).
+ // Convert each entry through the canonical bridge so the upload
+ // result mirrors what `resources-provider` writes into Apollo on
+ // initial hydration and what the `resourceAdded` subscription
+ // emits — keeping the cache shape internally consistent.
const raw = unwrapApiResponse(response);
- // TODO(backend): drop the `String(item.id)` / `String(item.userId)`
- // coercion once `POST /resources/` returns `id`/`userId` as strings.
- // The GraphQL `ID` scalar is typed as `string` everywhere; REST sends
- // numbers, so we normalize here to keep downstream consumers (forms,
- // Apollo cache, etc.) type-consistent.
const data: UploadResponse = {
- ...raw,
- items: (raw.items ?? []).map((item) => ({
- ...item,
- id: String(item.id),
- userId: String(item.userId),
- })),
+ items: (raw.items ?? []).map(restResourceEntryToFragment),
+ total: raw.total ?? 0,
};
const uploadedCount = data.items.length;
const message = buildUploadSuccessMessage(uploadedCount, options?.dir);
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index d854dbfe..4d527b44 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -211,7 +211,12 @@ const updateCacheForSubscription = (
return existingArray;
}
- const itemExists = existingArray.some((ref) => readField('id', ref) === newItem.id);
+ // ID equality must be type-tolerant: REST hydration writes some
+ // entries with `id` as a string (GraphQL `ID!` convention)
+ const targetId = String(newItem.id);
+ const idMatches = (ref: Reference) => String(readField('id', ref)) === targetId;
+
+ const itemExists = existingArray.some(idMatches);
let newRef = toReference(newItem as StoreObject, true);
@@ -226,7 +231,7 @@ const updateCacheForSubscription = (
const action = resolveSubscriptionAction(subscriptionName);
return cacheActionStrategies[action](existingArray, newRef, itemExists, () =>
- existingArray.filter((ref) => readField('id', ref) !== newItem.id),
+ existingArray.filter((ref) => !idMatches(ref)),
);
},
},
diff --git a/frontend/src/providers/resources-provider.tsx b/frontend/src/providers/resources-provider.tsx
index 1a42b7a3..68fa602f 100644
--- a/frontend/src/providers/resources-provider.tsx
+++ b/frontend/src/providers/resources-provider.tsx
@@ -5,6 +5,7 @@ import { toast } from 'sonner';
import type { UserResourceFragmentFragment } from '@/graphql/types';
import { RESOURCES_API_PATH } from '@/features/resources/resources-constants';
+import { restResourceEntryToFragment, type RestResourceList } from '@/features/resources/resources-rest';
import { useResourcesRealtime } from '@/features/resources/use-resources-realtime';
import { ResourcesDocument, useResourcesQuery } from '@/graphql/types';
import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';
@@ -22,17 +23,6 @@ interface ResourcesContextValue {
resources: UserResourceFragmentFragment[];
}
-/**
- * Shape of the REST `GET /resources/` response wrapper.
- * The element type is intentionally aliased to the GraphQL fragment — the backend's
- * `models.ResourceEntry` is meant to be structurally identical, and we treat them as
- * the same type so REST-loaded entries can sit in the same Apollo cache as GraphQL ones.
- */
-interface ResourcesListResponse {
- items?: null | UserResourceFragmentFragment[];
- total?: number;
-}
-
interface ResourcesProviderProps {
children: ReactNode;
}
@@ -45,16 +35,16 @@ const RESOURCES_ERROR_TOAST_ID = 'resources-error';
* Loads the user's full resource library and keeps it in sync via three GraphQL
* subscriptions (added / updated / deleted).
*
- * **Temporary detail**: the initial library is fetched via REST
- * `GET /resources/?recursive=true` rather than the GraphQL `resources` query.
- * The GraphQL resolver currently has a bug for `path == "" && recursive == true`
- * that returns only top-level entries — we side-step it by hydrating the same
- * Apollo cache slot from REST and reading it back through `useResourcesQuery`
- * with a `cache-only` fetch policy. Subscriptions continue to update the cache
- * as before, so consumers see no behavioural change.
+ * The initial library is fetched via REST `GET /resources/?recursive=true` and
+ * the result is written into the same Apollo cache slot that `useResourcesQuery`
+ * reads (via `cache-only` fetch policy). Subscriptions continue to update the
+ * cache through `lib/apollo.ts`, so consumers see one unified store.
*
- * Once the backend resolver is fixed this hook should switch back to a plain
- * `useResourcesQuery({ variables: { recursive: true } })`.
+ * NOTE: the equivalent GraphQL `resources(recursive: true)` query now works
+ * correctly for the root path. Switching this provider to a plain
+ * `useResourcesQuery({ variables: { recursive: true } })` is a viable follow-up
+ * once we no longer need the snake_case → camelCase conversion that REST
+ * requires (see `restResourceEntryToFragment`).
*/
export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
const { authInfo, isAuthenticated } = useUser();
@@ -82,7 +72,7 @@ export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
(async () => {
try {
- const response = await api.get<ResourcesListResponse>(RESOURCES_API_PATH, {
+ const response = await api.get<RestResourceList>(RESOURCES_API_PATH, {
params: { recursive: true },
});
const data = unwrapApiResponse(response);
@@ -91,23 +81,17 @@ export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
return;
}
- // `__typename` is required so Apollo normalizes each entry under
- // `UserResource:<id>` in the cache. Without it the read-back through
- // `useResourcesQuery` returns objects whose scalar fields are `undefined`
- // (the cache treats every entry as an unidentifiable structural blob).
- //
- // TODO(backend): remove `String(item.id)` / `String(item.userId)` coercion
- // once the REST `/resources/` endpoint returns `id`/`userId` as strings.
- // Currently it returns them as numbers, which breaks consumers that rely
- // on the GraphQL `ID` scalar (typed as `string` everywhere) — e.g. zod
- // validation `z.array(z.string())` in `FlowForm.resourceIds`.
+ // The REST endpoint returns `models.ResourceEntry` with snake_case
+ // JSON tags and numeric `id`/`user_id`. We convert each entry into the
+ // camelCase GraphQL fragment shape so it can sit in the same Apollo
+ // cache slot that subscriptions and the GraphQL `resources` query write
+ // to. `__typename` is added explicitly because Apollo refuses to
+ // normalise an object as `UserResource:<id>` without it.
apolloClient.writeQuery({
data: {
resources: (data.items ?? []).map((item) => ({
- ...item,
+ ...restResourceEntryToFragment(item),
__typename: 'UserResource' as const,
- id: String(item.id),
- userId: String(item.userId),
})),
},
query: ResourcesDocument,
@@ -158,7 +142,9 @@ export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
const value = useMemo<ResourcesContextValue>(
() => ({
error,
- getResource: (id: string) => resources.find((item) => item.id === id),
+ // `item.id` is canonically numeric (see `resources-rest.ts`) but typed
+ // as `string` by codegen — coerce both sides for the lookup.
+ getResource: (id: string) => resources.find((item) => String(item.id) === id),
isInitialLoading,
isLoading: restLoading,
refetch: () => {