@myrialabs/clopen 0.4.38 → 0.4.39

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 (114) hide show
  1. package/backend/auth/permissions.ts +25 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +5 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  9. package/backend/database/queries/deploy-queries.ts +124 -0
  10. package/backend/database/queries/graph-queries.ts +291 -247
  11. package/backend/database/queries/index.ts +4 -0
  12. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  13. package/backend/database/queries/integration-queries.ts +34 -6
  14. package/backend/db-client/integrations/index.ts +37 -0
  15. package/backend/db-client/integrations/links.ts +533 -0
  16. package/backend/db-client/integrations/projector.test.ts +280 -0
  17. package/backend/db-client/integrations/projector.ts +256 -0
  18. package/backend/db-client/integrations/supabase-service.ts +266 -0
  19. package/backend/db-client/providers/registry.ts +27 -0
  20. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  21. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  22. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  23. package/backend/db-client/providers/supabase/client.ts +259 -0
  24. package/backend/db-client/providers/supabase/features.ts +502 -0
  25. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  26. package/backend/db-client/providers/supabase/local.ts +137 -0
  27. package/backend/db-client/providers/types.ts +137 -0
  28. package/backend/deployments/bindings.test.ts +43 -0
  29. package/backend/deployments/bindings.ts +216 -0
  30. package/backend/deployments/index.ts +53 -0
  31. package/backend/deployments/log-streams.ts +214 -0
  32. package/backend/deployments/prompts.ts +70 -0
  33. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  34. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  35. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  36. package/backend/deployments/providers/vercel/client.ts +203 -0
  37. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  38. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  39. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  40. package/backend/deployments/providers/vercel/types.ts +104 -0
  41. package/backend/deployments/registry.ts +27 -0
  42. package/backend/deployments/service.ts +458 -0
  43. package/backend/deployments/types.ts +278 -0
  44. package/backend/index.ts +4 -0
  45. package/backend/integrations/projections/index.ts +0 -0
  46. package/backend/integrations/projections/mcp-projector.ts +7 -3
  47. package/backend/integrations/projections/types.ts +21 -9
  48. package/backend/integrations/registry/index.ts +5 -1
  49. package/backend/integrations/registry/providers/supabase.ts +61 -0
  50. package/backend/integrations/registry/providers/vercel.ts +46 -0
  51. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  52. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  53. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  54. package/backend/memory/README.md +57 -34
  55. package/backend/memory/compose.test.ts +3 -3
  56. package/backend/memory/compose.ts +6 -9
  57. package/backend/memory/config.ts +0 -5
  58. package/backend/memory/consolidate.ts +1 -2
  59. package/backend/memory/context.test.ts +8 -54
  60. package/backend/memory/context.ts +19 -25
  61. package/backend/memory/extract/episodic.ts +10 -12
  62. package/backend/memory/extract/index.ts +23 -52
  63. package/backend/memory/extract/scheduler.ts +3 -6
  64. package/backend/memory/index.ts +6 -5
  65. package/backend/memory/invalidate.ts +36 -48
  66. package/backend/memory/layout.ts +319 -130
  67. package/backend/memory/retention.ts +12 -42
  68. package/backend/memory/retrieval.eval.test.ts +2 -2
  69. package/backend/memory/retrieval.test.ts +228 -183
  70. package/backend/memory/retrieval.ts +22 -21
  71. package/backend/memory/revise.test.ts +62 -116
  72. package/backend/memory/revise.ts +0 -1
  73. package/backend/memory/view.ts +8 -5
  74. package/backend/snapshot/helpers.ts +35 -41
  75. package/backend/snapshot/snapshot-service.ts +90 -0
  76. package/backend/snapshot/turn-changes.test.ts +163 -0
  77. package/backend/snapshot/turn-changes.ts +131 -0
  78. package/backend/ws/db-client/accounts.ts +225 -0
  79. package/backend/ws/db-client/connections.ts +34 -3
  80. package/backend/ws/db-client/context.ts +37 -0
  81. package/backend/ws/db-client/index.ts +20 -1
  82. package/backend/ws/db-client/supabase.ts +188 -0
  83. package/backend/ws/deployments/actions.ts +360 -0
  84. package/backend/ws/deployments/context.ts +43 -0
  85. package/backend/ws/deployments/crud.ts +152 -0
  86. package/backend/ws/deployments/index.ts +15 -0
  87. package/backend/ws/deployments/schemas.ts +183 -0
  88. package/backend/ws/index.ts +6 -2
  89. package/backend/ws/memory/crud.ts +4 -16
  90. package/backend/ws/snapshot/changes.ts +279 -0
  91. package/backend/ws/snapshot/index.ts +4 -3
  92. package/dist/assets/{index-CyH7fSbR.js → index-BrF6nqld.js} +1 -1
  93. package/dist/assets/{index-DSHIANSy.js → index-C8Gi-b6U.js} +1 -1
  94. package/dist/assets/main-Bd3gb79F.css +1 -0
  95. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  96. package/dist/index.html +2 -2
  97. package/package.json +1 -1
  98. package/shared/constants/tool-icons.ts +9 -0
  99. package/shared/types/db-client/connection.ts +6 -0
  100. package/shared/types/db-client/index.ts +2 -0
  101. package/shared/types/db-client/integrations.ts +174 -0
  102. package/shared/types/db-client/supabase.ts +131 -0
  103. package/shared/types/deployments.ts +382 -0
  104. package/shared/types/memory.ts +34 -51
  105. package/shared/types/ui/components.ts +1 -1
  106. package/shared/utils/diff-calculator.test.ts +89 -0
  107. package/shared/utils/diff-calculator.ts +30 -65
  108. package/shared/utils/logger.ts +1 -0
  109. package/backend/memory/extract/languages.ts +0 -176
  110. package/backend/memory/extract/structural.test.ts +0 -215
  111. package/backend/memory/extract/structural.ts +0 -364
  112. package/backend/ws/snapshot/content.ts +0 -85
  113. package/dist/assets/main-D2IOjftb.css +0 -1
  114. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -139,6 +139,96 @@ export class SnapshotService {
139
139
  return this.sessionBaselines.get(sessionId) || {};
140
140
  }
141
141
 
142
+ // ========================================================================
143
+ // In-flight turn
144
+ // ========================================================================
145
+
146
+ /**
147
+ * Changes made since the last capture, for a turn that is still running.
148
+ *
149
+ * The settled source of truth is `captureSnapshot`, but it only lands when
150
+ * the stream ends — and the AI-change indicators have to light up while the
151
+ * model is still working. This answers the same question early, from the
152
+ * same baseline, without writing anything: no snapshot row, no baseline
153
+ * move, no dirty-set clear. Whatever it reports is replaced wholesale by the
154
+ * real capture a moment later.
155
+ *
156
+ * Candidates come from the file watcher's dirty set, so the cost is
157
+ * proportional to what actually changed rather than to repository size. The
158
+ * watcher only runs while a client is watching the project — which is
159
+ * exactly when a panel that renders these indicators is mounted — and any
160
+ * event it missed is recovered by the full scan at turn end.
161
+ */
162
+ /**
163
+ * The hash a file had when the running turn started.
164
+ *
165
+ * `known: false` means this session has no baseline at all, which is not the
166
+ * same as "the file is new" — the caller must not read an absent baseline as
167
+ * an empty file, or every file in the project would look freshly created.
168
+ */
169
+ getBaselineHash(sessionId: string, relativePath: string): { known: boolean; hash: string } {
170
+ const baseline = this.sessionBaselines.get(sessionId);
171
+ if (!baseline) return { known: false, hash: '' };
172
+ return { known: true, hash: baseline[relativePath] || '' };
173
+ }
174
+
175
+ async getPendingChanges(
176
+ projectPath: string,
177
+ scopeKey: string,
178
+ sessionId: string
179
+ ): Promise<SessionScopedChanges> {
180
+ // No baseline means this session has not captured or initialised yet.
181
+ // Building one here would hash the mid-turn disk state and declare it
182
+ // unchanged, blinding the indicators for the whole turn — so decline.
183
+ const baseline = this.sessionBaselines.get(sessionId);
184
+ if (!baseline) return {};
185
+
186
+ const dirty = fileWatcher.getDirtyFiles(scopeKey);
187
+ if (dirty.size === 0) return {};
188
+
189
+ // A path already in the baseline passed the gitignore-aware scan once, so
190
+ // it needs no second opinion. Only genuinely new paths do, and only those
191
+ // make us pay for a scan.
192
+ let eligible: Set<string> | null = null;
193
+ const hasNewPaths = Array.from(dirty).some((relativePath) => !(relativePath in baseline));
194
+ if (hasNewPaths) {
195
+ try {
196
+ const files = await getSnapshotFiles(projectPath);
197
+ eligible = new Set(
198
+ files.map((filepath) => path.relative(projectPath, filepath).replace(/\\/g, '/'))
199
+ );
200
+ } catch (error) {
201
+ debug.warn('snapshot', 'Pending-change scan failed, reporting tracked files only:', error);
202
+ }
203
+ }
204
+
205
+ const changes: SessionScopedChanges = {};
206
+
207
+ for (const relativePath of dirty) {
208
+ // An unknown path is only reported once the scan has vouched for it —
209
+ // so a build artifact or an ignored temp file never becomes a dot.
210
+ const oldHash = baseline[relativePath] || '';
211
+ if (!oldHash && !eligible?.has(relativePath)) continue;
212
+
213
+ const fullPath = path.join(projectPath, relativePath);
214
+ try {
215
+ const stat = await fs.stat(fullPath);
216
+ if (stat.size > MAX_FILE_SIZE) continue;
217
+
218
+ const result = await blobStore.hashFile(relativePath, fullPath);
219
+ if (result.hash !== oldHash) {
220
+ changes[relativePath] = { oldHash, newHash: result.hash };
221
+ }
222
+ } catch {
223
+ // Gone from disk: a deletion when we knew the file, nothing otherwise
224
+ // (a temp file the turn created and removed again).
225
+ if (oldHash) changes[relativePath] = { oldHash, newHash: '' };
226
+ }
227
+ }
228
+
229
+ return changes;
230
+ }
231
+
142
232
  // ========================================================================
143
233
  // Snapshot Capture
144
234
  // ========================================================================
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Turning a checkpoint's stored hashes into a file list.
3
+ *
4
+ * This is what every AI-change surface counts on: the dot in Files, the gutter
5
+ * in the editor, and the Changes tab all describe the same turn, so a file that
6
+ * this function drops is a change the user is never told about. The cases that
7
+ * matter are the ones where a side is absent — a creation, a deletion, a blob
8
+ * the store no longer has — because each of those used to be either invisible
9
+ * or a diff of nothing.
10
+ */
11
+
12
+ import { describe, it, expect } from 'bun:test';
13
+
14
+ import {
15
+ buildTurnFiles,
16
+ statusOf,
17
+ isBinaryBuffer,
18
+ summariseTurnFiles,
19
+ excerptPrompt
20
+ } from './turn-changes';
21
+
22
+ /** Blob reader over an in-memory store, so the tests own their failure modes. */
23
+ function readerFor(blobs: Record<string, string | Buffer>) {
24
+ return async (hash: string): Promise<Buffer> => {
25
+ const value = blobs[hash];
26
+ if (value === undefined) throw new Error(`missing blob ${hash}`);
27
+ return Buffer.isBuffer(value) ? value : Buffer.from(value, 'utf8');
28
+ };
29
+ }
30
+
31
+ describe('statusOf', () => {
32
+ it('reads a missing old side as a creation and a missing new side as a deletion', () => {
33
+ expect(statusOf('', 'new')).toBe('added');
34
+ expect(statusOf('old', '')).toBe('deleted');
35
+ expect(statusOf('old', 'new')).toBe('modified');
36
+ });
37
+ });
38
+
39
+ describe('isBinaryBuffer', () => {
40
+ it('calls a NUL byte binary and plain text not', () => {
41
+ expect(isBinaryBuffer(Buffer.from([0x68, 0x00, 0x69]))).toBe(true);
42
+ expect(isBinaryBuffer(Buffer.from('hello\nworld', 'utf8'))).toBe(false);
43
+ });
44
+ });
45
+
46
+ describe('buildTurnFiles', () => {
47
+ it('counts a modification with the lines that actually changed', async () => {
48
+ const files = await buildTurnFiles(
49
+ { 'src/a.ts': { oldHash: 'h1', newHash: 'h2' } },
50
+ readerFor({ h1: 'a\nb\nc\n', h2: 'a\nB\nc\n' })
51
+ );
52
+
53
+ expect(files).toEqual([
54
+ {
55
+ path: 'src/a.ts',
56
+ status: 'modified',
57
+ insertions: 1,
58
+ deletions: 1,
59
+ isBinary: false,
60
+ contentAvailable: true
61
+ }
62
+ ]);
63
+ });
64
+
65
+ it('counts a created file as all insertions', async () => {
66
+ const [file] = await buildTurnFiles(
67
+ { 'src/new.ts': { oldHash: '', newHash: 'h2' } },
68
+ readerFor({ h2: 'one\ntwo\n' })
69
+ );
70
+
71
+ expect(file.status).toBe('added');
72
+ expect(file.insertions).toBe(2);
73
+ expect(file.deletions).toBe(0);
74
+ });
75
+
76
+ it('reports a deleted file, which a tool-call reading could never see', async () => {
77
+ const [file] = await buildTurnFiles(
78
+ { 'src/gone.ts': { oldHash: 'h1', newHash: '' } },
79
+ readerFor({ h1: 'one\ntwo\nthree\n' })
80
+ );
81
+
82
+ expect(file.status).toBe('deleted');
83
+ expect(file.insertions).toBe(0);
84
+ expect(file.deletions).toBe(3);
85
+ });
86
+
87
+ it('keeps a binary file in the list but does not pretend to count its lines', async () => {
88
+ const [file] = await buildTurnFiles(
89
+ { 'assets/logo.png': { oldHash: 'h1', newHash: 'h2' } },
90
+ readerFor({ h1: Buffer.from([0x89, 0x00, 0x01]), h2: Buffer.from([0x89, 0x00, 0x02]) })
91
+ );
92
+
93
+ expect(file.isBinary).toBe(true);
94
+ expect(file.insertions).toBe(0);
95
+ expect(file.deletions).toBe(0);
96
+ expect(file.contentAvailable).toBe(true);
97
+ });
98
+
99
+ it('keeps the row when a blob is gone, flagged so the UI can say why', async () => {
100
+ const [file] = await buildTurnFiles(
101
+ { 'src/a.ts': { oldHash: 'missing', newHash: 'h2' } },
102
+ readerFor({ h2: 'a\n' })
103
+ );
104
+
105
+ expect(file.status).toBe('modified');
106
+ expect(file.contentAvailable).toBe(false);
107
+ expect(file.insertions).toBe(0);
108
+ expect(file.deletions).toBe(0);
109
+ });
110
+
111
+ it('orders files by path, so a refetch does not move rows under the cursor', async () => {
112
+ const files = await buildTurnFiles(
113
+ {
114
+ 'src/z.ts': { oldHash: '', newHash: 'h' },
115
+ 'src/a.ts': { oldHash: '', newHash: 'h' },
116
+ 'README.md': { oldHash: '', newHash: 'h' }
117
+ },
118
+ readerFor({ h: 'x\n' })
119
+ );
120
+
121
+ expect(files.map((f) => f.path)).toEqual(['README.md', 'src/a.ts', 'src/z.ts']);
122
+ });
123
+
124
+ it('answers an empty turn with an empty list', async () => {
125
+ expect(await buildTurnFiles({}, readerFor({}))).toEqual([]);
126
+ });
127
+ });
128
+
129
+ describe('summariseTurnFiles', () => {
130
+ it('adds up a turn for its header', async () => {
131
+ const files = await buildTurnFiles(
132
+ {
133
+ 'src/a.ts': { oldHash: 'h1', newHash: 'h2' },
134
+ 'src/b.ts': { oldHash: '', newHash: 'h3' }
135
+ },
136
+ readerFor({ h1: 'a\n', h2: 'b\n', h3: 'c\nd\n' })
137
+ );
138
+
139
+ expect(summariseTurnFiles(files)).toEqual({
140
+ filesChanged: 2,
141
+ insertions: 3,
142
+ deletions: 1
143
+ });
144
+ });
145
+ });
146
+
147
+ describe('excerptPrompt', () => {
148
+ it('returns a short prompt whole, trimmed', () => {
149
+ expect(excerptPrompt(' make the theme green ', 20)).toBe('make the theme green');
150
+ });
151
+
152
+ it('marks a cut prompt, so a row never reads as the whole question', () => {
153
+ expect(excerptPrompt('abcdefghij', 5)).toBe('abcde…');
154
+ });
155
+
156
+ it('does not leave the ellipsis hanging off a space', () => {
157
+ expect(excerptPrompt('abc def ghi', 4)).toBe('abc…');
158
+ });
159
+
160
+ it('answers empty for an empty prompt', () => {
161
+ expect(excerptPrompt(' ', 10)).toBe('');
162
+ });
163
+ });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Per-turn file changes, read from checkpoint snapshots.
3
+ *
4
+ * This is the source of truth for "what did this turn change", and it is
5
+ * deliberately NOT derived from tool calls. A snapshot is a gitignore-aware
6
+ * disk diff, so it sees a file rewritten by `sed`, a formatter, a codemod, an
7
+ * `apply_patch`, a notebook edit or a sub-agent — none of which necessarily
8
+ * surface as an Edit/Write tool_use, and several of which reach the frontend
9
+ * with their inputs stripped (see subagent-wire-trim.ts). Reading the disk
10
+ * instead of the transcript means a tool that does not exist yet is already
11
+ * handled.
12
+ *
13
+ * The trade-off is honest and must stay visible in the UI: a turn's delta is
14
+ * everything that changed on disk while the turn ran, which can include the
15
+ * user's own save or a build artifact that no .gitignore covers. It is "changed
16
+ * during this turn", not "provably written by the model".
17
+ */
18
+
19
+ import type { SessionScopedChanges } from '$shared/types/database/schema';
20
+ import { countLineChanges, isBinaryBuffer } from '$shared/utils/diff-calculator';
21
+
22
+ export { isBinaryBuffer };
23
+
24
+ export type TurnFileStatus = 'added' | 'modified' | 'deleted';
25
+
26
+ export interface TurnFileChange {
27
+ /** Project-relative path with forward slashes, as stored in the snapshot. */
28
+ path: string;
29
+ status: TurnFileStatus;
30
+ insertions: number;
31
+ deletions: number;
32
+ isBinary: boolean;
33
+ /**
34
+ * False when a blob this file needs is no longer readable. The change still
35
+ * happened — only its content is gone — so the row is kept and the UI says
36
+ * so, rather than rendering a diff of nothing.
37
+ */
38
+ contentAvailable: boolean;
39
+ }
40
+
41
+ /** Which way a file moved, decided by which side of the change has content. */
42
+ export function statusOf(oldHash: string, newHash: string): TurnFileStatus {
43
+ if (!oldHash) return 'added';
44
+ if (!newHash) return 'deleted';
45
+ return 'modified';
46
+ }
47
+
48
+ /**
49
+ * Turn one checkpoint's `session_changes` into a displayable file list.
50
+ *
51
+ * `readBlob` is injected so this stays a pure function over its inputs — the
52
+ * only I/O is the reader the caller hands in.
53
+ */
54
+ export async function buildTurnFiles(
55
+ changes: SessionScopedChanges,
56
+ readBlob: (hash: string) => Promise<Buffer>
57
+ ): Promise<TurnFileChange[]> {
58
+ const files: TurnFileChange[] = [];
59
+
60
+ for (const [path, change] of Object.entries(changes)) {
61
+ const status = statusOf(change.oldHash, change.newHash);
62
+
63
+ let oldBuf: Buffer | null = null;
64
+ let newBuf: Buffer | null = null;
65
+ let contentAvailable = true;
66
+
67
+ if (change.oldHash) {
68
+ try {
69
+ oldBuf = await readBlob(change.oldHash);
70
+ } catch {
71
+ contentAvailable = false;
72
+ }
73
+ }
74
+ if (change.newHash) {
75
+ try {
76
+ newBuf = await readBlob(change.newHash);
77
+ } catch {
78
+ contentAvailable = false;
79
+ }
80
+ }
81
+
82
+ const isBinary =
83
+ (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
84
+
85
+ let insertions = 0;
86
+ let deletions = 0;
87
+ if (contentAvailable && !isBinary) {
88
+ const counts = countLineChanges(
89
+ oldBuf ? oldBuf.toString('utf8') : '',
90
+ newBuf ? newBuf.toString('utf8') : ''
91
+ );
92
+ insertions = counts.additions;
93
+ deletions = counts.deletions;
94
+ }
95
+
96
+ files.push({ path, status, insertions, deletions, isBinary, contentAvailable });
97
+ }
98
+
99
+ // Alphabetical: a turn's file list is read as a checklist, and a stable order
100
+ // is what lets the eye return to the same row after a refetch.
101
+ files.sort((a, b) => a.path.localeCompare(b.path));
102
+ return files;
103
+ }
104
+
105
+ /**
106
+ * The prompt excerpt a turn row shows.
107
+ *
108
+ * Bounded because a single instruction can run to thousands of characters and
109
+ * every turn of the chat is sent at once, but cut marks itself with an ellipsis:
110
+ * a row that silently ends mid-sentence reads as the whole question.
111
+ */
112
+ export function excerptPrompt(text: string, limit: number): string {
113
+ const trimmed = text.trim();
114
+ if (trimmed.length <= limit) return trimmed;
115
+ return `${trimmed.slice(0, limit).trimEnd()}…`;
116
+ }
117
+
118
+ /** Roll a turn's file list up into the numbers a turn header shows. */
119
+ export function summariseTurnFiles(files: TurnFileChange[]): {
120
+ filesChanged: number;
121
+ insertions: number;
122
+ deletions: number;
123
+ } {
124
+ let insertions = 0;
125
+ let deletions = 0;
126
+ for (const file of files) {
127
+ insertions += file.insertions;
128
+ deletions += file.deletions;
129
+ }
130
+ return { filesChanged: files.length, insertions, deletions };
131
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * db-client — account-backed connections.
3
+ *
4
+ * db-client:providers database providers, for the link dialog
5
+ * db-client:accounts connected accounts that can supply one
6
+ * db-client:remote-databases what an account can reach
7
+ * db-client:create-options organisations and regions, for creating one
8
+ * db-client:create-group create the owning organisation
9
+ * db-client:create-database provision a new database and link it
10
+ * db-client:rename-database rename it at the provider
11
+ * db-client:delete-database destroy it at the provider, and unlink
12
+ * db-client:link bring one in
13
+ * db-client:update-link relabel / change mode / rotate the password
14
+ * db-client:unlink drop it, releasing the projected connection
15
+ * db-client:detect-local a `supabase start` stack in the working tree
16
+ * db-client:adopt-local turn that into an ordinary connection
17
+ *
18
+ * ADMIN-GATED, unlike the rest of this router. Linking projects a row that
19
+ * every admin sees, and it reads a credential belonging to the install rather
20
+ * than to the caller — the same reason `integrations:*` is admin-only. The
21
+ * ordinary connection routes stay open to members, who keep managing their own
22
+ * connections exactly as before.
23
+ */
24
+
25
+ import { t } from 'elysia';
26
+ import { createRouter } from '$shared/utils/ws-server';
27
+ import { initializeDatabase } from '../../database';
28
+ import { dbClientConnectionQueries } from '../../database/queries';
29
+ import { dbLinks, supabaseSurface } from '../../db-client/integrations';
30
+ import { localConnectionInput } from '../../db-client/providers/supabase/local';
31
+ import { ws as wsServer } from '$backend/utils/ws';
32
+ import { getDbClientPrincipal } from './access';
33
+ import { resolveDbClientProject } from './context';
34
+ import { debug } from '$shared/utils/logger';
35
+
36
+ /**
37
+ * Tell every client the connection list changed.
38
+ *
39
+ * Global rather than per-user: a projected connection is visible to every
40
+ * admin, so a client that only watched its own request would miss one appearing
41
+ * because a colleague linked it.
42
+ */
43
+ function announce(): void {
44
+ wsServer.emit.global('db-client:connections-changed', {});
45
+ }
46
+
47
+ export const accountsHandler = createRouter()
48
+ .http('db-client:providers', {
49
+ data: t.Object({}),
50
+ response: t.Object({
51
+ providers: t.Array(t.Any()),
52
+ accounts: t.Array(t.Any()),
53
+ links: t.Array(t.Any())
54
+ })
55
+ }, async () => {
56
+ await initializeDatabase();
57
+ return {
58
+ providers: dbLinks.providers(),
59
+ accounts: dbLinks.accounts(),
60
+ links: dbLinks.allLinks()
61
+ };
62
+ })
63
+
64
+ .http('db-client:remote-databases', {
65
+ data: t.Object({ accountId: t.String({ minLength: 1 }) }),
66
+ response: t.Array(t.Any())
67
+ }, async ({ data }) => {
68
+ return dbLinks.remoteDatabases(data.accountId);
69
+ })
70
+
71
+ .http('db-client:create-options', {
72
+ data: t.Object({ accountId: t.String({ minLength: 1 }) }),
73
+ response: t.Nullable(t.Any())
74
+ }, async ({ data }) => {
75
+ return dbLinks.createOptions(data.accountId);
76
+ })
77
+
78
+ .http('db-client:create-group', {
79
+ data: t.Object({
80
+ accountId: t.String({ minLength: 1 }),
81
+ name: t.String({ minLength: 1 })
82
+ }),
83
+ response: t.Object({ value: t.String(), label: t.String() })
84
+ }, async ({ data }) => {
85
+ await initializeDatabase();
86
+ return dbLinks.createGroup(data.accountId, data.name);
87
+ })
88
+
89
+ .http('db-client:create-database', {
90
+ data: t.Object({
91
+ accountId: t.String({ minLength: 1 }),
92
+ name: t.String({ minLength: 1 }),
93
+ group: t.String({ minLength: 1 }),
94
+ region: t.String({ minLength: 1 })
95
+ }),
96
+ response: t.Object({ link: t.Any(), ready: t.Boolean() })
97
+ }, async ({ data }) => {
98
+ await initializeDatabase();
99
+ // Provisioning plus the readiness wait runs past the default socket
100
+ // budget by design, so the call carries its own — a long budget, not an
101
+ // unbounded one, for the reason the Deployments surface settled on.
102
+ const result = await dbLinks.createDatabase(data);
103
+ announce();
104
+ return result;
105
+ })
106
+
107
+ .http('db-client:rename-database', {
108
+ data: t.Object({
109
+ accountId: t.String({ minLength: 1 }),
110
+ remoteRef: t.String({ minLength: 1 }),
111
+ name: t.String({ minLength: 1 })
112
+ }),
113
+ response: t.Object({ ok: t.Boolean() })
114
+ }, async ({ data }) => {
115
+ await dbLinks.renameDatabase(data.accountId, data.remoteRef, data.name);
116
+ return { ok: true };
117
+ })
118
+
119
+ .http('db-client:delete-database', {
120
+ data: t.Object({
121
+ accountId: t.String({ minLength: 1 }),
122
+ remoteRef: t.String({ minLength: 1 })
123
+ }),
124
+ response: t.Object({ ok: t.Boolean() })
125
+ }, async ({ data }) => {
126
+ await dbLinks.deleteDatabase(data.accountId, data.remoteRef);
127
+ announce();
128
+ return { ok: true };
129
+ })
130
+
131
+ .http('db-client:link', {
132
+ data: t.Object({
133
+ accountId: t.String({ minLength: 1 }),
134
+ remoteRef: t.String({ minLength: 1 }),
135
+ label: t.Optional(t.String()),
136
+ mode: t.Optional(t.String()),
137
+ secrets: t.Record(t.String(), t.String())
138
+ }),
139
+ response: t.Any()
140
+ }, async ({ data }) => {
141
+ await initializeDatabase();
142
+ const link = await dbLinks.create({
143
+ accountId: data.accountId,
144
+ remoteRef: data.remoteRef,
145
+ label: data.label,
146
+ mode: data.mode,
147
+ secrets: data.secrets
148
+ });
149
+ announce();
150
+ return link;
151
+ })
152
+
153
+ .http('db-client:update-link', {
154
+ data: t.Object({
155
+ linkId: t.String({ minLength: 1 }),
156
+ label: t.Optional(t.String()),
157
+ mode: t.Optional(t.String()),
158
+ secrets: t.Optional(t.Record(t.String(), t.String())),
159
+ refreshEndpoint: t.Optional(t.Boolean())
160
+ }),
161
+ response: t.Any()
162
+ }, async ({ data }) => {
163
+ const link = await dbLinks.update(data.linkId, {
164
+ label: data.label,
165
+ mode: data.mode,
166
+ secrets: data.secrets,
167
+ refreshEndpoint: data.refreshEndpoint
168
+ });
169
+ announce();
170
+ return link;
171
+ })
172
+
173
+ .http('db-client:unlink', {
174
+ data: t.Object({ linkId: t.String({ minLength: 1 }) }),
175
+ response: t.Object({ ok: t.Boolean() })
176
+ }, async ({ data }) => {
177
+ await dbLinks.remove(data.linkId);
178
+ announce();
179
+ return { ok: true };
180
+ })
181
+
182
+ .http('db-client:detect-local', {
183
+ data: t.Object({ projectId: t.Optional(t.String()) }),
184
+ response: t.Nullable(t.Any())
185
+ }, async ({ data, conn }) => {
186
+ const project = resolveDbClientProject(conn, data.projectId);
187
+ if (!project) return null;
188
+ const local = await supabaseSurface.detectLocal(project.root);
189
+ if (!local) return null;
190
+ return {
191
+ ref: local.ref,
192
+ configPath: local.configPath,
193
+ dbPort: local.dbPort,
194
+ // True when a connection to this stack already exists, so the panel
195
+ // offers "open" rather than "add" and never creates a duplicate.
196
+ alreadyAdded: dbClientConnectionQueries
197
+ .list()
198
+ .some((connection) => {
199
+ const marker = connection.options?.supabase as { ref?: string } | undefined;
200
+ return marker?.ref === local.ref;
201
+ })
202
+ };
203
+ })
204
+
205
+ .http('db-client:adopt-local', {
206
+ data: t.Object({ projectId: t.Optional(t.String()) }),
207
+ response: t.Any()
208
+ }, async ({ data, conn }) => {
209
+ await initializeDatabase();
210
+ const project = resolveDbClientProject(conn, data.projectId);
211
+ if (!project) throw new Error('No project is open');
212
+
213
+ const local = await supabaseSurface.detectLocal(project.root);
214
+ if (!local) throw new Error('No supabase/config.toml in this project');
215
+
216
+ // Owned by the caller, NOT by the install: a local stack is a developer's
217
+ // own database, and it is created from an ordinary member-visible route
218
+ // rather than from an account. It is not a projection and nothing
219
+ // re-derives it.
220
+ const { userId } = getDbClientPrincipal(conn);
221
+ const created = dbClientConnectionQueries.createForUser(localConnectionInput(local), userId);
222
+ debug.log('db-client', `Adopted local Supabase stack ${local.ref} as ${created.id}`);
223
+ announce();
224
+ return created;
225
+ });
@@ -14,6 +14,7 @@ import type {
14
14
  DbSslMode
15
15
  } from '$shared/types/db-client';
16
16
  import { debug } from '$shared/utils/logger';
17
+ import { dbLinks } from '../../db-client/integrations';
17
18
  import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
18
19
 
19
20
  const driverSchema = t.Union([
@@ -101,6 +102,20 @@ function normalizeSshPatch(input: DbClientConnectionInput['ssh']): DbClientConne
101
102
  };
102
103
  }
103
104
 
105
+ /**
106
+ * The fields a user may still change on a derived connection.
107
+ *
108
+ * A projection owns where the connection points and what it logs in with. The
109
+ * colour is decoration, and the name is what the user calls it in their own
110
+ * list — neither is derived from anything, so neither is taken away.
111
+ */
112
+ function pickLocalFields(patch: Partial<DbClientConnectionInput>): Partial<DbClientConnectionInput> {
113
+ const local: Partial<DbClientConnectionInput> = {};
114
+ if (patch.name !== undefined) local.name = patch.name;
115
+ if (patch.color !== undefined) local.color = patch.color;
116
+ return local;
117
+ }
118
+
104
119
  function ensureInputDefaults(input: DbClientConnectionInput): DbClientConnectionInput {
105
120
  return {
106
121
  ...input,
@@ -117,7 +132,10 @@ export const connectionsHandler = createRouter()
117
132
  }, async ({ conn }) => {
118
133
  await initializeDatabase();
119
134
  const { userId, isAdmin } = getDbClientPrincipal(conn);
120
- return dbClientConnectionQueries.listForUser(userId, isAdmin);
135
+ // Ownership is attached HERE rather than stored on the connection: the
136
+ // answer lives in `integration_projections`, and duplicating it into a
137
+ // column would create a second place for it to be wrong.
138
+ return dbLinks.decorate(dbClientConnectionQueries.listForUser(userId, isAdmin));
121
139
  })
122
140
 
123
141
  .http('db-client:get', {
@@ -127,7 +145,7 @@ export const connectionsHandler = createRouter()
127
145
  const { userId, isAdmin } = getDbClientPrincipal(conn);
128
146
  const connection = dbClientConnectionQueries.getForUser(data.id, userId, isAdmin);
129
147
  if (!connection) throw new Error('db-client connection not found');
130
- return connection;
148
+ return { ...connection, managedBy: dbLinks.managedBy(data.id) };
131
149
  })
132
150
 
133
151
  .http('db-client:create', {
@@ -153,7 +171,13 @@ export const connectionsHandler = createRouter()
153
171
  }, async ({ data, conn }) => {
154
172
  const { userId, isAdmin } = getDbClientPrincipal(conn);
155
173
  requireDbClientConnectionAccess(conn, data.id);
156
- const patch = data.patch as Partial<DbClientConnectionInput>;
174
+ // A managed row is DERIVED. Letting the form edit its host or password
175
+ // would produce a connection the next re-projection silently reverts, so
176
+ // the two fields that are genuinely local are the only ones allowed
177
+ // through — everything else is changed by editing the link.
178
+ const patch = (dbLinks.isManaged(data.id)
179
+ ? pickLocalFields(data.patch as Partial<DbClientConnectionInput>)
180
+ : data.patch) as Partial<DbClientConnectionInput>;
157
181
  const normalized: Partial<DbClientConnectionInput> = {
158
182
  ...patch,
159
183
  ssh: patch.ssh ? normalizeSshPatch(patch.ssh) : undefined
@@ -169,6 +193,13 @@ export const connectionsHandler = createRouter()
169
193
  }, async ({ data, conn }) => {
170
194
  const { userId, isAdmin } = getDbClientPrincipal(conn);
171
195
  requireDbClientConnectionAccess(conn, data.id);
196
+ // Deleting a projected row here would leave the account owning a
197
+ // connection that no longer exists, and the next re-projection would
198
+ // recreate it — so the panel is told to unlink instead, which is the
199
+ // operation that actually means "I do not want this connection".
200
+ if (dbLinks.isManaged(data.id)) {
201
+ throw new Error('This connection comes from a connected account. Unlink it there to remove it.');
202
+ }
172
203
  await connectionManager.release(data.id);
173
204
  dbClientConnectionQueries.deleteForUser(data.id, userId, isAdmin);
174
205
  return { ok: true };