@processfocus/runtime-local 0.1.0-next.3 → 0.1.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +3 -0
  2. package/dist/authentication-server.mjs +3 -3
  3. package/dist/{chunk-bg5r4wpv.js → chunk-3wzp2sax.js} +168 -117
  4. package/dist/{chunk-cbd36jq1.js → chunk-5kjvzbwr.js} +1 -1
  5. package/dist/{chunk-727y6qkb.js → chunk-egeb4821.js} +2 -2
  6. package/dist/{chunk-d4ctj079.js → chunk-q5v72erd.js} +2 -2
  7. package/dist/{chunk-04r0t2mb.js → chunk-wvbz0nmd.js} +97 -49
  8. package/dist/{chunk-r5s2v669.js → chunk-y8fnwbx0.js} +512 -480
  9. package/dist/dashboard-source/apps/frontend/app/(protected)/connected-apps/disconnect-form.tsx +57 -0
  10. package/dist/dashboard-source/apps/frontend/app/(protected)/connected-apps/page.tsx +97 -0
  11. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/list-page-client.tsx +26 -1
  12. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/page.tsx +11 -12
  13. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-create-form.tsx +7 -5
  14. package/dist/dashboard-source/apps/frontend/app/api/dev/import-events/route.ts +69 -1
  15. package/dist/dashboard-source/apps/frontend/app/app-shell.tsx +4 -3
  16. package/dist/dashboard-source/apps/frontend/app/mcp/[[...endpoint]]/route.ts +0 -3
  17. package/dist/dashboard-source/apps/frontend/components/Header.tsx +10 -0
  18. package/dist/dashboard-source/apps/frontend/lib/collections/collection-provider-factory.tsx +3 -2
  19. package/dist/dashboard-source/apps/frontend/lib/collections/graphql-stream.ts +21 -1
  20. package/dist/dashboard-source/apps/frontend/lib/dev/import-completed-query-invalidation.tsx +66 -9
  21. package/dist/dashboard-source/apps/frontend/lib/dev/import-completed-refresh.ts +10 -6
  22. package/dist/dashboard-source/apps/frontend/lib/generated/gql/gql.ts +3 -3
  23. package/dist/dashboard-source/apps/frontend/lib/generated/gql/graphql.ts +2 -3
  24. package/dist/dashboard-source/apps/frontend/lib/mcp/oauth.ts +61 -72
  25. package/dist/dashboard-source/apps/frontend/lib/mcp/origin.ts +20 -12
  26. package/dist/dashboard-source/apps/frontend/lib/mcp/store.ts +80 -166
  27. package/dist/dashboard-source/apps/frontend/lib/mcp/todos.ts +42 -19
  28. package/dist/dashboard-source/apps/frontend/package.json +2 -3
  29. package/dist/dashboard-source/modules/shadcn-components/src/lib/date-time-display.tsx +3 -2
  30. package/dist/dashboard-source.json +2 -3
  31. package/dist/graphql-server.mjs +34 -7
  32. package/dist/job-worker-supervisor.mjs +3 -3
  33. package/dist/job-worker.mjs +5 -5
  34. package/dist/main.mjs +7 -2
  35. package/dist/resources/graphql-schema/system.graphql +1 -0
  36. package/package.json +3 -4
@@ -0,0 +1,57 @@
1
+ "use client"
2
+
3
+ import { useActionState, useId } from "react"
4
+ import { Button } from "../../../../../modules/shadcn-components/src/index.ts"
5
+ import { DateTimeDisplay } from "../../../../../modules/shadcn-components/src/lib/date-time-display.tsx"
6
+
7
+ export function DisconnectForm({
8
+ action,
9
+ name,
10
+ access,
11
+ authorisedAt,
12
+ clientId,
13
+ grantId,
14
+ }: {
15
+ action: (previous: string | null, form: FormData) => Promise<string | null>
16
+ name: string
17
+ access: string
18
+ authorisedAt: number
19
+ clientId: string
20
+ grantId: string
21
+ }) {
22
+ const nameId = useId()
23
+ const [error, submit, pending] = useActionState(action, null)
24
+ return (
25
+ <form action={submit} aria-labelledby={nameId} className="space-y-2">
26
+ <div className="flex flex-wrap items-center justify-between gap-3">
27
+ <div className="min-w-0 [overflow-wrap:anywhere]">
28
+ <p id={nameId} className="font-medium">
29
+ {name}
30
+ </p>
31
+ <p className="text-sm text-muted-foreground">{access}</p>
32
+ <p className="text-sm text-muted-foreground">
33
+ Authorised on{" "}
34
+ <DateTimeDisplay
35
+ kind="timestamp"
36
+ value={authorisedAt}
37
+ initialMode="browser-local"
38
+ seconds="milliseconds"
39
+ />
40
+ </p>
41
+ </div>
42
+ <input type="hidden" name="client" value={clientId} />
43
+ <input type="hidden" name="grant" value={grantId} />
44
+ <Button
45
+ type="submit"
46
+ variant="outline"
47
+ disabled={pending}
48
+ aria-busy={pending}
49
+ aria-label={`Disconnect ${name}`}
50
+ >
51
+ Disconnect
52
+ </Button>
53
+ </div>
54
+ <div role="status">{error}</div>
55
+ </form>
56
+ )
57
+ }
@@ -0,0 +1,97 @@
1
+ import { Effect } from "effect"
2
+ import type { Metadata } from "next"
3
+ import { refresh } from "next/cache"
4
+ import { headers } from "next/headers"
5
+ import { DisconnectForm } from "./disconnect-form.tsx"
6
+ import { getSessionWithTokenAndExpiry } from "@/lib/auth/session"
7
+ import { BasePage } from "@/lib/effect/runtime"
8
+ import { disconnectConnection, listConnections } from "@/lib/mcp/oauth"
9
+ import { mcpOriginForHost } from "@/lib/mcp/origin"
10
+
11
+ export const metadata: Metadata = { title: "Connected apps" }
12
+ export const instant = false
13
+
14
+ async function connectionAccount(requestHeaders: Headers) {
15
+ const origin = mcpOriginForHost(requestHeaders.get("host"))
16
+ if (!origin) return null
17
+ const session = await getSessionWithTokenAndExpiry()
18
+ if (
19
+ !session ||
20
+ !("email" in session) ||
21
+ !session.humanSession ||
22
+ session.delegation
23
+ )
24
+ return null
25
+ return { origin, userId: session.userId, email: session.email }
26
+ }
27
+
28
+ async function disconnect(_previous: string | null, form: FormData) {
29
+ "use server"
30
+ const requestHeaders = await headers()
31
+ const account = await connectionAccount(requestHeaders)
32
+ const clientId = form.get("client")
33
+ const grantId = form.get("grant")
34
+ const disconnected =
35
+ account &&
36
+ requestHeaders.get("origin") === account.origin &&
37
+ typeof clientId === "string" &&
38
+ typeof grantId === "string" &&
39
+ (await disconnectConnection({ ...account, clientId, grantId }))
40
+
41
+ if (!disconnected) return "Unable to disconnect the app. Try again."
42
+ // An action redirect renders through the internal host, which has a different
43
+ // MCP grant partition. Refresh the current page on its existing origin.
44
+ refresh()
45
+ return null
46
+ }
47
+
48
+ export default BasePage.build(() =>
49
+ Effect.promise(async () => {
50
+ const account = await connectionAccount(await headers())
51
+ const connections = account
52
+ ? await listConnections(account.origin, account.userId)
53
+ : []
54
+ return (
55
+ <div className="mx-auto w-full max-w-3xl space-y-6 p-4 sm:p-6">
56
+ <div>
57
+ <h1 className="text-2xl font-semibold">Connected apps</h1>
58
+ <p className="mt-2 text-sm text-muted-foreground">
59
+ Manage the MCP apps you’ve authorised for this environment.
60
+ </p>
61
+ </div>
62
+ {account ? (
63
+ <>
64
+ <div className="space-y-1 text-sm text-muted-foreground [overflow-wrap:anywhere]">
65
+ <p>Environment: {account.origin}</p>
66
+ <p>Signed in as {account.email}</p>
67
+ </div>
68
+ {connections.length > 0 ? (
69
+ <ul className="divide-y rounded-lg border">
70
+ {connections.map(
71
+ ({ id, clientId, name, access, authorisedAt }) => (
72
+ <li key={id} className="p-4">
73
+ <DisconnectForm
74
+ action={disconnect}
75
+ name={name}
76
+ access={access}
77
+ authorisedAt={authorisedAt}
78
+ clientId={clientId}
79
+ grantId={id}
80
+ />
81
+ </li>
82
+ ),
83
+ )}
84
+ </ul>
85
+ ) : (
86
+ <p className="text-sm text-muted-foreground">
87
+ No connected apps.
88
+ </p>
89
+ )}
90
+ </>
91
+ ) : (
92
+ <p role="alert">MCP connections are unavailable for this session.</p>
93
+ )}
94
+ </div>
95
+ )
96
+ }),
97
+ )
@@ -44,6 +44,7 @@ import {
44
44
  CollectionTableCard,
45
45
  type CollectionTableColumn,
46
46
  } from "@/components/collections/collection-table-card"
47
+ import { useDevImportRevision } from "@/lib/dev/import-completed-query-invalidation"
47
48
  import { useGraphqlClient } from "@/lib/graphql/client-provider"
48
49
  import {
49
50
  type AvailableList,
@@ -238,6 +239,14 @@ function triggerDownload(url: string): void {
238
239
  link.remove()
239
240
  }
240
241
 
242
+ function isCurrentList(pathname: string, listPath: string) {
243
+ try {
244
+ return decodeURIComponent(pathname) === `/lists${listPath}`
245
+ } catch {
246
+ return false
247
+ }
248
+ }
249
+
241
250
  export function ListControlsClient({
242
251
  currentList,
243
252
  listPath,
@@ -260,6 +269,20 @@ export function ListControlsClient({
260
269
  const isPushingUrl = useRef(false)
261
270
  const [exporting, setExporting] = useState(false)
262
271
  const [exportError, setExportError] = useState<string | null>(null)
272
+ const [creating, setCreating] = useState(false)
273
+ const revision = useDevImportRevision()
274
+ const renderedRevision = useRef(revision)
275
+ useEffect(() => {
276
+ if (
277
+ revision === renderedRevision.current ||
278
+ creating ||
279
+ !isCurrentList(pathname, listPath)
280
+ )
281
+ return
282
+ // A retained table catches up once its create, detail or process dialog closes.
283
+ renderedRevision.current = revision
284
+ router.refresh()
285
+ }, [revision, creating, pathname, listPath, router])
263
286
 
264
287
  useEffect(() => {
265
288
  if (!isPushingUrl.current) {
@@ -270,7 +293,7 @@ export function ListControlsClient({
270
293
 
271
294
  useEffect(() => {
272
295
  // Defer pending filters while this List is the background of a process dialog.
273
- if (decodeURIComponent(pathname) !== `/lists${listPath}`) return
296
+ if (!isCurrentList(pathname, listPath)) return
274
297
  if (debouncedFilterValue !== filter) {
275
298
  isPushingUrl.current = true
276
299
  const newSearch = applyListFilterToSearchParams(
@@ -359,6 +382,8 @@ export function ListControlsClient({
359
382
  ) : null}
360
383
  {currentList.canCreate ? (
361
384
  <ListCreateButton
385
+ open={creating}
386
+ onOpenChange={setCreating}
362
387
  listPath={listPath}
363
388
  name={currentList.detailName ?? currentList.name}
364
389
  />
@@ -8,6 +8,7 @@ import { BasePage, runEffect } from "@/lib/effect/runtime"
8
8
  import { GraphQLService } from "@/lib/effect/services/graphql"
9
9
  import {
10
10
  type AvailableList,
11
+ type ListSortInput,
11
12
  availableListsQuery,
12
13
  buildListQueryVariables,
13
14
  fetchListData,
@@ -37,8 +38,7 @@ interface ListDataSectionProps {
37
38
  readonly page: number
38
39
  readonly limit: number
39
40
  readonly filter: string
40
- readonly sortField: string | null
41
- readonly sortDirection: string | null
41
+ readonly sort: ListSortInput | null
42
42
  }
43
43
 
44
44
  function ListDataSkeleton() {
@@ -115,12 +115,9 @@ async function ListDataSection({
115
115
  page,
116
116
  limit,
117
117
  filter,
118
- sortField,
119
- sortDirection,
118
+ sort,
120
119
  }: ListDataSectionProps) {
121
120
  "use memo"
122
-
123
- const sort = parseListSort(sortField, sortDirection)
124
121
  const session = await runEffect(
125
122
  getSessionWithToken.pipe(Effect.catch(() => Effect.succeed(null))),
126
123
  )
@@ -174,10 +171,6 @@ const ListPage = Effect.fn("ListPage")(function* (props: PageProps) {
174
171
  const page = parseListPageNumber(searchParams.page, 1)
175
172
  const limit = parseListPageSize(searchParams.limit, 20)
176
173
  const filter = searchParams.filter ?? ""
177
- const sort = parseListSort(
178
- searchParams.sort ?? null,
179
- searchParams.dir ?? null,
180
- )
181
174
  const availableLists = yield* graphql
182
175
  .request<{ readonly availableLists: readonly AvailableList[] }>(
183
176
  availableListsQuery,
@@ -202,6 +195,13 @@ const ListPage = Effect.fn("ListPage")(function* (props: PageProps) {
202
195
  return <ListNotFound listPath={listPath} />
203
196
  }
204
197
 
198
+ // A saved URL can outlive the column it sorts by.
199
+ const sort = currentList.outputColumns.some(
200
+ (column) => column.sortable && column.field === searchParams.sort,
201
+ )
202
+ ? parseListSort(searchParams.sort ?? null, searchParams.dir ?? null)
203
+ : null
204
+
205
205
  return (
206
206
  <div className="container mx-auto py-6">
207
207
  <Suspense fallback={null}>
@@ -225,8 +225,7 @@ const ListPage = Effect.fn("ListPage")(function* (props: PageProps) {
225
225
  page={page}
226
226
  limit={limit}
227
227
  filter={filter}
228
- sortField={searchParams.sort ?? null}
229
- sortDirection={searchParams.dir ?? null}
228
+ sort={sort}
230
229
  />
231
230
  </Suspense>
232
231
  </div>
@@ -2,7 +2,6 @@
2
2
 
3
3
  import { useQuery } from "@tanstack/react-query"
4
4
  import { ClientError } from "graphql-request"
5
- import { useState } from "react"
6
5
  import type { FieldError, FormActionsContext } from "../../../../../../modules/form/src/index.ts"
7
6
  import { Button } from "../../../../../../modules/shadcn-components/src/index.ts"
8
7
  import { ListSchemaForm } from "./list-schema-form.tsx"
@@ -29,15 +28,18 @@ function objectValue(value: unknown): Record<string, unknown> | null {
29
28
  export function ListCreateButton({
30
29
  listPath,
31
30
  name,
31
+ open,
32
+ onOpenChange,
32
33
  }: {
33
34
  listPath: string
34
35
  name: string
36
+ open: boolean
37
+ onOpenChange: (open: boolean) => void
35
38
  }) {
36
- const [open, setOpen] = useState(false)
37
39
  return (
38
40
  <>
39
- <Button onClick={() => setOpen(true)}>Create record</Button>
40
- <Dialog open={open} onOpenChange={setOpen}>
41
+ <Button onClick={() => onOpenChange(true)}>Create record</Button>
42
+ <Dialog open={open} onOpenChange={onOpenChange}>
41
43
  <DialogContent className="max-h-[90vh] overflow-y-auto">
42
44
  <DialogHeader>
43
45
  <DialogTitle>Create {name}</DialogTitle>
@@ -45,7 +47,7 @@ export function ListCreateButton({
45
47
  {open ? (
46
48
  <ListCreateForm
47
49
  listPath={listPath}
48
- onClose={() => setOpen(false)}
50
+ onClose={() => onOpenChange(false)}
49
51
  />
50
52
  ) : null}
51
53
  </DialogContent>
@@ -1,9 +1,62 @@
1
+ import { mkdirSync, readFileSync, watch } from "node:fs"
2
+ import { join, resolve } from "node:path"
3
+ import { Schema } from "effect"
1
4
  import { connection } from "next/server"
2
5
  import { addImportCompletedSubscriber } from "@/lib/dev/import-completed-events"
3
6
 
4
7
  const encoder = new TextEncoder()
8
+ const decodeReady = Schema.decodeUnknownSync(
9
+ Schema.fromJsonString(
10
+ Schema.Struct({
11
+ revision: Schema.String,
12
+ processPaths: Schema.Array(Schema.String),
13
+ }),
14
+ ),
15
+ )
5
16
 
6
- export async function GET() {
17
+ // Register before reading: a save between subscribing and the initial read
18
+ // cannot be missed. EventSource supplies the last delivered revision on reconnect.
19
+ function subscribeToGraphqlReady(
20
+ directory: string,
21
+ lastRevision: string | null,
22
+ controller: ReadableStreamDefaultController<Uint8Array>,
23
+ ) {
24
+ let revision = lastRevision
25
+ mkdirSync(directory, { recursive: true })
26
+ const watcher = watch(directory, (_, name) => {
27
+ if (!name || name === "ready.json") publish()
28
+ })
29
+ function fail(error: unknown) {
30
+ watcher.close()
31
+ controller.error(error)
32
+ }
33
+ function publish() {
34
+ try {
35
+ const ready = decodeReady(
36
+ readFileSync(join(directory, "ready.json"), "utf8"),
37
+ )
38
+ if (ready.revision === revision) return
39
+ // The initial read refreshes list discovery without restarting replication.
40
+ const payload = {
41
+ processPaths: revision === null ? [] : ready.processPaths,
42
+ }
43
+ revision = ready.revision
44
+ controller.enqueue(
45
+ encoder.encode(`id: ${revision}\ndata: ${JSON.stringify(payload)}\n\n`),
46
+ )
47
+ } catch (error) {
48
+ // The Dashboard can start before the first GraphQL listener.
49
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
50
+ return
51
+ fail(error)
52
+ }
53
+ }
54
+ watcher.on("error", fail)
55
+ publish()
56
+ return () => watcher.close()
57
+ }
58
+
59
+ export async function GET(request: Request) {
7
60
  if (process.env.NODE_ENV !== "development") {
8
61
  return new Response("Not found", { status: 404 })
9
62
  }
@@ -15,6 +68,21 @@ export async function GET() {
15
68
  start(controller) {
16
69
  controller.enqueue(encoder.encode(": connected\n\n"))
17
70
 
71
+ const org = process.env["PF_ORG"]
72
+ if (process.env["PF_LOCAL_GRAPHQL_IMPORT"] === "1" && org) {
73
+ const directory = resolve(
74
+ process.env["NX_WORKSPACE_ROOT"] ?? process.cwd(),
75
+ org,
76
+ ".processfocus/local-graphql",
77
+ )
78
+ unsubscribe = subscribeToGraphqlReady(
79
+ directory,
80
+ request.headers.get("last-event-id"),
81
+ controller,
82
+ )
83
+ return
84
+ }
85
+
18
86
  unsubscribe = addImportCompletedSubscriber({
19
87
  send: (payload) => {
20
88
  controller.enqueue(
@@ -14,7 +14,7 @@ import { OrgSettingsProvider } from "@/components/org-settings-provider"
14
14
  import { SidebarProvider } from "@/components/ui/sidebar"
15
15
  import { getSessionCacheScope } from "@/lib/auth/session-cache-scope"
16
16
  import type { CurrentProviderUser } from "@/lib/current-provider-user"
17
- import { DevImportCompletedQueryInvalidation } from "@/lib/dev/import-completed-query-invalidation"
17
+ import { DevImportCompletedProvider } from "@/lib/dev/import-completed-query-invalidation"
18
18
  import type { FeaturePermissions } from "@/lib/feature-permissions"
19
19
  import { isExecutionsPath } from "@/lib/mobile-shell-policy"
20
20
  import { getQueryClient } from "@/lib/query-client"
@@ -73,7 +73,6 @@ export function AppShell({
73
73
 
74
74
  return (
75
75
  <QueryClientProvider client={queryClient}>
76
- <DevImportCompletedQueryInvalidation />
77
76
  <FeaturePermissionsProvider value={featurePermissions}>
78
77
  <OrgSettingsProvider startDayOfWeek={orgIdentity?.startDayOfWeek ?? 0}>
79
78
  <MocksProvider>
@@ -94,7 +93,9 @@ export function AppShell({
94
93
  initialProviderUser={providerUser}
95
94
  />
96
95
  <main className="flex-1 px-4 pt-4 pb-10 sm:px-8 sm:pt-6 sm:pb-16 lg:px-12">
97
- <ListRefreshProvider>{children}</ListRefreshProvider>
96
+ <DevImportCompletedProvider>
97
+ <ListRefreshProvider>{children}</ListRefreshProvider>
98
+ </DevImportCompletedProvider>
98
99
  </main>
99
100
  </div>
100
101
  </SidebarProvider>
@@ -4,7 +4,6 @@ import {
4
4
  authorize,
5
5
  challenge,
6
6
  consent,
7
- manageConnections,
8
7
  readMcpAccess,
9
8
  register,
10
9
  resourceMetadata,
@@ -23,8 +22,6 @@ async function handle(
23
22
  if (!origin) return new Response(null, { status: 404 })
24
23
  const path = (await context.params).endpoint?.join("/") ?? ""
25
24
  if (path === "consent" && request.method !== "DELETE") return consent(request)
26
- if (path === "connections" && request.method !== "DELETE")
27
- return manageConnections(request, origin)
28
25
  if (request.method === "GET") {
29
26
  if (path === "authorize") return authorize(request, origin)
30
27
  if (path === "metadata") return authMetadata(origin)
@@ -8,6 +8,7 @@ import {
8
8
  LogOut,
9
9
  Monitor,
10
10
  Moon,
11
+ Plug,
11
12
  Sun,
12
13
  UserCog,
13
14
  UserRoundKey,
@@ -45,6 +46,7 @@ import { useRxDb } from "@/lib/collections/rxdb-provider"
45
46
  import type { CurrentProviderUser } from "@/lib/current-provider-user"
46
47
  import { useGraphqlClient } from "@/lib/graphql/client-provider"
47
48
  import { fetchCurrentProviderUser } from "@/lib/graphql/provider-user-queries"
49
+ import { connectedAppsPath } from "@/lib/mcp/origin"
48
50
  import {
49
51
  type ShellNavigationItem,
50
52
  getShellPolicy,
@@ -454,6 +456,14 @@ export function Header({
454
456
  </Link>
455
457
  </DropdownMenuItem>
456
458
  ) : null}
459
+ {isProviderUser && !delegation && !session.workload ? (
460
+ <DropdownMenuItem asChild>
461
+ <Link href={connectedAppsPath} prefetch={false}>
462
+ <Plug className="mr-2 h-4 w-4" aria-hidden="true" />
463
+ <span>Connected apps</span>
464
+ </Link>
465
+ </DropdownMenuItem>
466
+ ) : null}
457
467
  {canOpenActOnBehalfMenu(delegationListing) ? (
458
468
  <DropdownMenuItem asChild>
459
469
  <Link href="/act-on-behalf">
@@ -391,7 +391,8 @@ export function createCollectionProvider<TDoc extends RxDbDocumentBase>(
391
391
  try {
392
392
  await Promise.all([
393
393
  previousState.replicationState.cancel(),
394
- previousState.collection.cleanup(),
394
+ // Logout runs while the Dashboard's live queries are still mounted.
395
+ previousState.collection.cleanup({ dependents: true }),
395
396
  ])
396
397
  } catch (error) {
397
398
  console.error(
@@ -435,7 +436,7 @@ export function createCollectionProvider<TDoc extends RxDbDocumentBase>(
435
436
  if (previousState.status === "ready") {
436
437
  return Promise.all([
437
438
  previousState.replicationState.cancel(),
438
- previousState.collection.cleanup(),
439
+ previousState.collection.cleanup({ dependents: true }),
439
440
  ])
440
441
  .then(() => undefined)
441
442
  .catch((error: unknown) => {
@@ -102,7 +102,27 @@ export function createGraphQLStream<TDoc>({
102
102
  active = false
103
103
  unsubscribe()
104
104
  removeConnected()
105
- removeGraphQLWebSocketRef(url)
105
+ const shared = GRAPHQL_WEBSOCKET_BY_URL.get(url)
106
+ if (shared?.refCount !== 1) {
107
+ removeGraphQLWebSocketRef(url)
108
+ return
109
+ }
110
+ // RxDB drops the dispose promise on final release. Evict synchronously
111
+ // so the replacement gets a new client, then observe the pending retry.
112
+ shared.refCount = 0
113
+ GRAPHQL_WEBSOCKET_BY_URL.delete(url)
114
+ void Promise.resolve(client.dispose()).catch((error: unknown) => {
115
+ if (
116
+ typeof error === "object" &&
117
+ error !== null &&
118
+ "code" in error &&
119
+ error.code === 1000 &&
120
+ "reason" in error &&
121
+ error.reason === "All Subscriptions Gone"
122
+ )
123
+ return
124
+ onError(error)
125
+ })
106
126
  }
107
127
  },
108
128
  }
@@ -1,12 +1,22 @@
1
1
  "use client"
2
2
 
3
3
  import { useQueryClient } from "@tanstack/react-query"
4
- import { useEffect, useEffectEvent } from "react"
4
+ import { usePathname } from "next/navigation"
5
+ import {
6
+ type ReactNode,
7
+ createContext,
8
+ useContext,
9
+ useEffect,
10
+ useEffectEvent,
11
+ useRef,
12
+ useState,
13
+ } from "react"
5
14
  import type { ImportCompletedPayload } from "./import-completed-events.ts"
6
15
  import {
7
16
  invalidateImportCompletedQueries,
8
17
  refreshImportCompletedCollections,
9
18
  } from "./import-completed-refresh.ts"
19
+ import { parseListReturnDestination } from "@/app/(protected)/lists/lib/list-refresh"
10
20
  import { useSession } from "@/components/auth-provider"
11
21
  import { useRuntimeConfig } from "@/components/config-provider"
12
22
 
@@ -26,10 +36,42 @@ const parseImportCompletedPayload = (
26
36
  }
27
37
  }
28
38
 
29
- export function DevImportCompletedQueryInvalidation() {
39
+ const ImportRevision = createContext<string | null>(null)
40
+
41
+ export const useDevImportRevision = () => useContext(ImportRevision)
42
+
43
+ export function DevImportCompletedProvider({
44
+ children,
45
+ }: {
46
+ children: ReactNode
47
+ }) {
30
48
  const queryClient = useQueryClient()
31
49
  const runtimeConfig = useRuntimeConfig()
32
50
  const session = useSession()
51
+ const pathname = usePathname()
52
+ const deferredProcessImport = useRef<ImportCompletedPayload | null>(null)
53
+ const lastEventId = useRef<string | null>(null)
54
+ const [revision, setRevision] = useState<string | null>(null)
55
+ const refreshImport = useEffectEvent((payload: ImportCompletedPayload) => {
56
+ void invalidateImportCompletedQueries(queryClient, payload)
57
+ void refreshImportCompletedCollections(
58
+ runtimeConfig,
59
+ session.userId,
60
+ payload,
61
+ )
62
+ })
63
+
64
+ // Refetching form defaults or recreating draft replication can reset inputs in a
65
+ // retained List's process dialog. Apply the latest import after leaving the form.
66
+ useEffect(() => {
67
+ if (
68
+ !pathname.startsWith("/processes/start/") &&
69
+ deferredProcessImport.current
70
+ ) {
71
+ refreshImport(deferredProcessImport.current)
72
+ deferredProcessImport.current = null
73
+ }
74
+ }, [pathname])
33
75
 
34
76
  const handleMessage = useEffectEvent((event: MessageEvent<string>) => {
35
77
  let payload: ImportCompletedPayload | null
@@ -40,12 +82,23 @@ export function DevImportCompletedQueryInvalidation() {
40
82
  }
41
83
 
42
84
  if (payload) {
43
- void invalidateImportCompletedQueries(queryClient, payload)
44
- void refreshImportCompletedCollections(
45
- runtimeConfig,
46
- session.userId,
47
- payload,
48
- )
85
+ if (event.lastEventId) {
86
+ if (event.lastEventId === lastEventId.current) return
87
+ // The first receipt establishes the baseline for this connection.
88
+ if (lastEventId.current !== null) setRevision(event.lastEventId)
89
+ lastEventId.current = event.lastEventId
90
+ }
91
+ const url = new URL(window.location.href)
92
+ if (
93
+ payload.processPaths.length &&
94
+ url.pathname.startsWith("/processes/start/") &&
95
+ parseListReturnDestination(url.searchParams.get("returnTo"), url.origin)
96
+ ) {
97
+ deferredProcessImport.current = payload
98
+ void invalidateImportCompletedQueries(queryClient, { processPaths: [] })
99
+ } else {
100
+ refreshImport(payload)
101
+ }
49
102
  }
50
103
  })
51
104
 
@@ -58,5 +111,9 @@ export function DevImportCompletedQueryInvalidation() {
58
111
  return () => events.close()
59
112
  }, [])
60
113
 
61
- return null
114
+ return (
115
+ <ImportRevision.Provider value={revision}>
116
+ {children}
117
+ </ImportRevision.Provider>
118
+ )
62
119
  }
@@ -8,14 +8,18 @@ export const invalidateImportCompletedQueries = (
8
8
  queryClient: QueryClient,
9
9
  payload: ImportCompletedPayload,
10
10
  ) => {
11
- if (payload.processPaths.length === 0) {
12
- return Promise.resolve()
13
- }
14
-
15
- return queryClient.invalidateQueries({
16
- queryKey: formMetadataQueryKey,
11
+ const lists = queryClient.invalidateQueries({
12
+ queryKey: ["availableLists"],
17
13
  refetchType: "active",
18
14
  })
15
+ if (payload.processPaths.length === 0) return lists
16
+ return Promise.all([
17
+ lists,
18
+ queryClient.invalidateQueries({
19
+ queryKey: formMetadataQueryKey,
20
+ refetchType: "active",
21
+ }),
22
+ ])
19
23
  }
20
24
 
21
25
  export const refreshImportCompletedCollections = async (