@myrialabs/clopen 0.4.38 → 0.4.40

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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -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/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,188 @@
1
+ /**
2
+ * db-client — the Supabase surface.
3
+ *
4
+ * Every route starts by resolving a SCOPE: is this connection Supabase, and is
5
+ * there an account behind it or only a local stack. A connection that is
6
+ * neither answers `null` rather than an error, because the panel asks
7
+ * speculatively when a connection is selected and "this is not Supabase" is an
8
+ * ordinary answer.
9
+ *
10
+ * Access is checked the way the rest of this router checks it — the caller must
11
+ * be able to reach the CONNECTION — plus a project-access check inside
12
+ * `resolveDbClientProject` for the routes that touch the working tree. Reads
13
+ * are open to whoever can use the connection; applying a migration and writing
14
+ * types are not, and say so.
15
+ */
16
+
17
+ import { t } from 'elysia';
18
+ import { createRouter } from '$shared/utils/ws-server';
19
+ import { resolveSupabaseScope, supabaseSurface, type SupabaseScope } from '../../db-client/integrations';
20
+ import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
21
+ import { resolveDbClientProject } from './context';
22
+ import type { WSConnection } from '$shared/utils/ws-server';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ async function scopeFor(
26
+ conn: WSConnection,
27
+ connectionId: string,
28
+ projectId?: string
29
+ ): Promise<SupabaseScope | null> {
30
+ requireDbClientConnectionAccess(conn, connectionId);
31
+ const project = resolveDbClientProject(conn, projectId);
32
+ return resolveSupabaseScope(connectionId, project?.root ?? null);
33
+ }
34
+
35
+ /**
36
+ * A scope, or a readable failure.
37
+ *
38
+ * Used by every route that only makes sense for Supabase: reaching one of these
39
+ * on a plain Postgres connection means the panel offered a tab it should not
40
+ * have, and saying so beats returning an empty list that reads like "nothing
41
+ * here".
42
+ */
43
+ async function requireScope(
44
+ conn: WSConnection,
45
+ connectionId: string,
46
+ projectId?: string
47
+ ): Promise<SupabaseScope> {
48
+ const scope = await scopeFor(conn, connectionId, projectId);
49
+ if (!scope) throw new Error('This connection is not a Supabase project');
50
+ return scope;
51
+ }
52
+
53
+ /**
54
+ * Writes are admin-only.
55
+ *
56
+ * Applying a migration changes a schema everyone shares, and writing generated
57
+ * types writes a file into the repository. Both are outward-facing in the sense
58
+ * `Task 3` uses: the consequence outlives the request.
59
+ */
60
+ function requireAdmin(conn: WSConnection, action: string): void {
61
+ const { isAdmin } = getDbClientPrincipal(conn);
62
+ if (!isAdmin) throw new Error(`Only an admin can ${action}`);
63
+ }
64
+
65
+ const connectionTarget = {
66
+ connectionId: t.String({ minLength: 1 }),
67
+ projectId: t.Optional(t.String())
68
+ };
69
+
70
+ export const supabaseHandler = createRouter()
71
+ .http('db-client:supabase-context', {
72
+ data: t.Object(connectionTarget),
73
+ response: t.Nullable(t.Any())
74
+ }, async ({ data, conn }) => {
75
+ const scope = await scopeFor(conn, data.connectionId, data.projectId);
76
+ if (!scope) return null;
77
+ return {
78
+ ...supabaseSurface.context(scope),
79
+ hasLocalProject: scope.local !== null,
80
+ hasAccount: scope.remote !== null,
81
+ accountLabel: scope.accountLabel,
82
+ // Only meaningful for an account-backed connection; a local stack never
83
+ // touches the Management API, so it has no budget to report.
84
+ rateLimit: await supabaseSurface.rateLimit(scope)
85
+ };
86
+ })
87
+
88
+ .http('db-client:supabase-migrations', {
89
+ data: t.Object(connectionTarget),
90
+ response: t.Any()
91
+ }, async ({ data, conn }) => {
92
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
93
+ return supabaseSurface.migrations(scope);
94
+ })
95
+
96
+ .http('db-client:supabase-migration-sql', {
97
+ data: t.Object({ ...connectionTarget, version: t.String({ minLength: 1 }) }),
98
+ response: t.Object({ sql: t.String() })
99
+ }, async ({ data, conn }) => {
100
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
101
+ const report = await supabaseSurface.migrations(scope);
102
+ const migration = report.migrations.find((entry) => entry.version === data.version);
103
+ // The path is looked up rather than accepted, so this cannot be used to
104
+ // read a file outside the project's migrations directory.
105
+ if (!migration?.path) throw new Error(`Migration ${data.version} has no local file`);
106
+ return { sql: await supabaseSurface.migrationSql(migration.path) };
107
+ })
108
+
109
+ .http('db-client:supabase-apply-migration', {
110
+ data: t.Object({ ...connectionTarget, version: t.String({ minLength: 1 }) }),
111
+ response: t.Object({ version: t.String(), durationMs: t.Number() })
112
+ }, async ({ data, conn }) => {
113
+ requireAdmin(conn, 'apply a migration');
114
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
115
+ const result = await supabaseSurface.apply(scope, data.version);
116
+ debug.log('db-client', `Supabase migration ${result.version} applied to ${scope.context.ref}`);
117
+ return result;
118
+ })
119
+
120
+ .http('db-client:supabase-rls', {
121
+ data: t.Object(connectionTarget),
122
+ response: t.Any()
123
+ }, async ({ data, conn }) => {
124
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
125
+ return supabaseSurface.rls(scope);
126
+ })
127
+
128
+ .http('db-client:supabase-buckets', {
129
+ data: t.Object(connectionTarget),
130
+ response: t.Array(t.Any())
131
+ }, async ({ data, conn }) => {
132
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
133
+ return supabaseSurface.buckets(scope);
134
+ })
135
+
136
+ .http('db-client:supabase-auth-users', {
137
+ data: t.Object({
138
+ ...connectionTarget,
139
+ search: t.Optional(t.String()),
140
+ limit: t.Optional(t.Number()),
141
+ offset: t.Optional(t.Number())
142
+ }),
143
+ response: t.Any()
144
+ }, async ({ data, conn }) => {
145
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
146
+ return supabaseSurface.authUsers(scope, {
147
+ search: data.search,
148
+ limit: data.limit,
149
+ offset: data.offset
150
+ });
151
+ })
152
+
153
+ .http('db-client:supabase-functions', {
154
+ data: t.Object(connectionTarget),
155
+ response: t.Array(t.Any())
156
+ }, async ({ data, conn }) => {
157
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
158
+ return supabaseSurface.functions(scope);
159
+ })
160
+
161
+ .http('db-client:supabase-function-body', {
162
+ data: t.Object({ ...connectionTarget, slug: t.String({ minLength: 1 }) }),
163
+ response: t.Object({ body: t.String() })
164
+ }, async ({ data, conn }) => {
165
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
166
+ return { body: await supabaseSurface.functionBody(scope, data.slug) };
167
+ })
168
+
169
+ .http('db-client:supabase-types', {
170
+ data: t.Object({ ...connectionTarget, schemas: t.Optional(t.Array(t.String())) }),
171
+ response: t.Object({ types: t.String(), suggestedPath: t.String() })
172
+ }, async ({ data, conn }) => {
173
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
174
+ return supabaseSurface.types(scope, data.schemas ?? ['public']);
175
+ })
176
+
177
+ .http('db-client:supabase-write-types', {
178
+ data: t.Object({
179
+ ...connectionTarget,
180
+ path: t.String({ minLength: 1 }),
181
+ contents: t.String()
182
+ }),
183
+ response: t.Object({ path: t.String(), bytes: t.Number() })
184
+ }, async ({ data, conn }) => {
185
+ requireAdmin(conn, 'write generated types into the project');
186
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
187
+ return supabaseSurface.writeTypes(scope, data.path, data.contents);
188
+ });
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Acting on a deployment, and following one.
3
+ *
4
+ * deployments:action redeploy, cancel, roll back or promote
5
+ * deployments:send-logs a failed build's log, as chat-ready text
6
+ * deployments:follow-start begin streaming a running build's log
7
+ * deployments:follow-stop stop one stream
8
+ *
9
+ * `deployments:action` is the only route in this surface that changes anything
10
+ * outward-facing. The CONFIRMATION lives in the client, because that is where a
11
+ * human is: the dialog names the environment and the hostname that will change
12
+ * before this route is ever called. What the server owes in return is an
13
+ * audit-visible log line and an honest status — `pending` when the provider
14
+ * moves traffic asynchronously, never `done` on a promise.
15
+ *
16
+ * Nothing here is reachable by an agent. This surface exposes no MCP tool, so a
17
+ * build is only ever triggered by a person pressing a button.
18
+ */
19
+
20
+ import { t } from 'elysia';
21
+ import { createRouter } from '$shared/utils/ws-server';
22
+ import { gitService } from '$backend/git/git-service';
23
+ import { repoPathOf } from '$backend/deployments/bindings';
24
+ import {
25
+ buildDeployFailurePrompt,
26
+ deployService,
27
+ startBuildLogStream,
28
+ stopBuildLogStream,
29
+ stopBuildLogStreamsForUser
30
+ } from '$backend/deployments';
31
+ import { getProvider } from '$backend/integrations';
32
+ import { integrationAccountQueries } from '$backend/database/queries';
33
+ import type { DeployAction } from '$shared/types/deployments';
34
+ import { ws } from '$backend/utils/ws';
35
+ import { debug } from '$shared/utils/logger';
36
+ import { resolveDeployProject } from './context';
37
+ import { announceDeploymentsChanged } from './crud';
38
+ import {
39
+ ACTION_RESULT_SCHEMA,
40
+ DEPLOY_ACTION_SCHEMA,
41
+ PROJECT_STATUS_SCHEMA,
42
+ DEPLOY_INFO_SCHEMA,
43
+ DEPLOY_TARGET_SCHEMA,
44
+ NEW_PROJECT_DEFAULTS_SCHEMA
45
+ } from './schemas';
46
+
47
+ const PROJECT_FIELD = { projectId: t.Optional(t.String()) };
48
+
49
+ /**
50
+ * `owner/repo` for a working tree, or null.
51
+ *
52
+ * Soft on every failure: a project that is not a repository, or has no remote,
53
+ * simply has nothing to suggest — which is a normal state, not an error worth
54
+ * failing a dialog over.
55
+ */
56
+ /**
57
+ * The branch checked out right now, or null.
58
+ *
59
+ * Detached HEAD answers null rather than a commit hash: a hash is a valid ref
60
+ * to build, but offering one as a default would silently deploy a commit the
61
+ * user has not named — and on a detached HEAD they almost certainly meant a
62
+ * branch they have yet to pick.
63
+ */
64
+ async function localBranch(root: string): Promise<string | null> {
65
+ try {
66
+ const info = await gitService.getBranches(root);
67
+ return info.detached ? null : info.current || null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ async function localRepoPath(root: string): Promise<string | null> {
74
+ try {
75
+ const remotes = await gitService.getRemotes(root);
76
+ const origin = remotes.find((remote) => remote.name === 'origin') ?? remotes[0];
77
+ return origin ? repoPathOf(origin.fetchUrl || origin.pushUrl) : null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ export const deploymentsActionsHandler = createRouter()
84
+ .http('deployments:action', {
85
+ data: t.Object({
86
+ ...PROJECT_FIELD,
87
+ accountId: t.String({ minLength: 1 }),
88
+ deploymentId: t.String({ minLength: 1 }),
89
+ action: DEPLOY_ACTION_SCHEMA
90
+ }),
91
+ response: ACTION_RESULT_SCHEMA
92
+ }, async ({ data, conn }) => {
93
+ const { projectId, project } = resolveDeployProject(conn, data.projectId);
94
+ const action = data.action as DeployAction;
95
+
96
+ // Logged before the call, not after: if the provider hangs or the process
97
+ // dies mid-request, the record that someone asked for a production change
98
+ // is the thing worth having.
99
+ debug.log(
100
+ 'deployments',
101
+ `${ws.getUserId(conn)} requested ${action} on ${data.deploymentId} for project ${project.name}`
102
+ );
103
+
104
+ const result = await deployService.runAction(projectId, data.accountId, action, data.deploymentId);
105
+ announceDeploymentsChanged(projectId);
106
+ return result;
107
+ })
108
+
109
+ /**
110
+ * A failed build's log, as the text the chat will send.
111
+ *
112
+ * The text is handed BACK to the client rather than injected into a session
113
+ * here, for the reason the Issues surface hands its prompts back: the chat
114
+ * pipeline is browser-owned, and a second injection path would race it.
115
+ */
116
+ .http('deployments:send-logs', {
117
+ data: t.Object({
118
+ ...PROJECT_FIELD,
119
+ accountId: t.String({ minLength: 1 }),
120
+ deploymentId: t.String({ minLength: 1 })
121
+ }),
122
+ response: t.Object({ prompt: t.String() })
123
+ }, async ({ data, conn }) => {
124
+ const { projectId, project } = resolveDeployProject(conn, data.projectId);
125
+
126
+ const [deployment, bundle] = await Promise.all([
127
+ deployService.get(projectId, data.accountId, data.deploymentId),
128
+ deployService.fetchLogs(projectId, data.accountId, data.deploymentId)
129
+ ]);
130
+
131
+ const account = integrationAccountQueries.getById(data.accountId);
132
+ const providerName = account ? getProvider(account.provider)?.name ?? account.provider : 'the provider';
133
+
134
+ return {
135
+ prompt: buildDeployFailurePrompt(deployment, bundle, {
136
+ projectName: project.name,
137
+ providerName
138
+ })
139
+ };
140
+ })
141
+
142
+ .http('deployments:follow-start', {
143
+ data: t.Object({
144
+ ...PROJECT_FIELD,
145
+ accountId: t.String({ minLength: 1 }),
146
+ deploymentId: t.String({ minLength: 1 })
147
+ }),
148
+ response: t.Object({ streamId: t.String(), backlog: t.String() })
149
+ }, async ({ data, conn }) => {
150
+ const { projectId } = resolveDeployProject(conn, data.projectId);
151
+ const userId = ws.getUserId(conn);
152
+
153
+ const started = await startBuildLogStream(projectId, data.accountId, data.deploymentId, userId);
154
+ // The follow belongs to the socket that asked for it: closing the tab must
155
+ // close the request against the provider, not leave it open for the life
156
+ // of the process with nothing listening.
157
+ ws.addCleanup(conn, () => stopBuildLogStreamsForUser(userId));
158
+ return started;
159
+ })
160
+
161
+ .http('deployments:follow-stop', {
162
+ data: t.Object({ streamId: t.String({ minLength: 1 }) }),
163
+ response: t.Object({ ok: t.Boolean() })
164
+ }, async ({ data, conn }) => {
165
+ stopBuildLogStream(data.streamId, ws.getUserId(conn));
166
+ return { ok: true };
167
+ })
168
+
169
+ /**
170
+ * Start a new build.
171
+ *
172
+ * Its own route rather than a case of `deployments:action`, because it acts
173
+ * on a BRANCH rather than on an existing deployment — and a project that has
174
+ * never been deployed has no deployment to act on. That gap is what made the
175
+ * panel a dead end for exactly the project a user most wants to get live.
176
+ */
177
+ .http('deployments:deploy', {
178
+ data: t.Object({
179
+ ...PROJECT_FIELD,
180
+ accountId: t.String({ minLength: 1 }),
181
+ ref: t.String({ minLength: 1, maxLength: 255 }),
182
+ production: t.Boolean()
183
+ }),
184
+ response: ACTION_RESULT_SCHEMA
185
+ }, async ({ data, conn }) => {
186
+ const { projectId, project } = resolveDeployProject(conn, data.projectId);
187
+
188
+ debug.log(
189
+ 'deployments',
190
+ `${ws.getUserId(conn)} started a ${data.production ? 'production' : 'preview'} build of ${data.ref} for ${project.name}`
191
+ );
192
+
193
+ const result = await deployService.createDeployment(projectId, data.accountId, {
194
+ ref: data.ref,
195
+ production: data.production
196
+ });
197
+ announceDeploymentsChanged(projectId);
198
+ return result;
199
+ })
200
+
201
+ /**
202
+ * What the deploy dialog needs, composed from both sides.
203
+ *
204
+ * The adapter answers for the REMOTE project; the suggested repository comes
205
+ * from the LOCAL one. Composing here rather than in the adapter keeps the
206
+ * adapter free of any notion that a Clopen project has a working tree.
207
+ */
208
+ .http('deployments:project-status', {
209
+ data: t.Object({
210
+ ...PROJECT_FIELD,
211
+ accountId: t.String({ minLength: 1 })
212
+ }),
213
+ response: PROJECT_STATUS_SCHEMA
214
+ }, async ({ data, conn }) => {
215
+ const { projectId } = resolveDeployProject(conn, data.projectId);
216
+ return deployService.projectStatus(projectId, data.accountId);
217
+ })
218
+
219
+ .http('deployments:deploy-info', {
220
+ data: t.Object({
221
+ ...PROJECT_FIELD,
222
+ accountId: t.String({ minLength: 1 })
223
+ }),
224
+ response: DEPLOY_INFO_SCHEMA
225
+ }, async ({ data, conn }) => {
226
+ const { projectId, root } = resolveDeployProject(conn, data.projectId);
227
+
228
+ // Both run at once. They are independent — one asks the provider about
229
+ // the remote project, the other reads a file in the working tree — and
230
+ // running them in series was half of why this dialog felt slow.
231
+ const [info, suggestedRepo, currentBranch] = await Promise.all([
232
+ deployService.deployInfo(projectId, data.accountId),
233
+ localRepoPath(root),
234
+ localBranch(root)
235
+ ]);
236
+
237
+ // Only asked when it could matter. A project that already builds has
238
+ // nothing to connect, and the check costs another request.
239
+ const access =
240
+ !info.canDeploy && suggestedRepo
241
+ ? await deployService
242
+ .repositoryAccess(projectId, data.accountId, suggestedRepo)
243
+ .catch(() => ({ state: 'unknown' as const, reason: null, actionUrl: null }))
244
+ : { state: 'unavailable' as const, reason: null, actionUrl: null };
245
+
246
+ return {
247
+ ...info,
248
+ suggestedRepo,
249
+ connectState: access.state,
250
+ connectHint: access.reason,
251
+ connectUrl: access.actionUrl,
252
+ currentBranch
253
+ };
254
+ })
255
+
256
+ /**
257
+ * Attach a git repository to the bound remote project.
258
+ *
259
+ * Outward-facing in the sense that matters here: it changes how the remote
260
+ * project behaves for everyone, and it enables automatic deploys on push. The
261
+ * dialog that calls it names the repository first.
262
+ */
263
+ /** Whether a repository could be attached — asked before anything offers it. */
264
+ .http('deployments:repo-access', {
265
+ data: t.Object({
266
+ ...PROJECT_FIELD,
267
+ accountId: t.String({ minLength: 1 }),
268
+ gitRepo: t.String({ minLength: 1, maxLength: 255 })
269
+ }),
270
+ response: t.Object({
271
+ state: t.Union([t.Literal('ready'), t.Literal('blocked'), t.Literal('unknown')]),
272
+ reason: t.Union([t.String(), t.Null()]),
273
+ actionUrl: t.Union([t.String(), t.Null()])
274
+ })
275
+ }, async ({ data, conn }) => {
276
+ const { projectId } = resolveDeployProject(conn, data.projectId);
277
+ return deployService.repositoryAccess(projectId, data.accountId, data.gitRepo);
278
+ })
279
+
280
+ .http('deployments:connect-repo', {
281
+ data: t.Object({
282
+ ...PROJECT_FIELD,
283
+ accountId: t.String({ minLength: 1 }),
284
+ gitRepo: t.String({ minLength: 1, maxLength: 255 }),
285
+ gitProvider: t.Optional(t.Union([t.String(), t.Null()]))
286
+ }),
287
+ response: t.Object({ ok: t.Boolean() })
288
+ }, async ({ data, conn }) => {
289
+ const { projectId, project } = resolveDeployProject(conn, data.projectId);
290
+
291
+ debug.log(
292
+ 'deployments',
293
+ `${ws.getUserId(conn)} connected ${data.gitRepo} to the deploy target for ${project.name}`
294
+ );
295
+
296
+ await deployService.connectRepository(projectId, data.accountId, {
297
+ gitRepo: data.gitRepo,
298
+ gitProvider: data.gitProvider ?? 'github'
299
+ });
300
+ announceDeploymentsChanged(projectId);
301
+ return { ok: true };
302
+ })
303
+
304
+ /**
305
+ * What to prefill the new-project form with.
306
+ *
307
+ * Read from the LOCAL project, because it already answers both questions: a
308
+ * project called `calc-2` that pushes to `acme/calc-2` does not need the user
309
+ * to retype either. Failures are soft — an empty form is a working form.
310
+ */
311
+ .http('deployments:new-project-defaults', {
312
+ data: t.Object({ ...PROJECT_FIELD }),
313
+ response: NEW_PROJECT_DEFAULTS_SCHEMA
314
+ }, async ({ data, conn }) => {
315
+ const { project, root } = resolveDeployProject(conn, data.projectId);
316
+ const gitRepo = await localRepoPath(root);
317
+
318
+ return {
319
+ // Vercel project names are lowercase and hyphenated; offering a name
320
+ // that will be rejected is worse than offering none.
321
+ suggestedName: project.name.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''),
322
+ gitRepo,
323
+ gitProvider: gitRepo ? 'github' : null
324
+ };
325
+ })
326
+
327
+ .http('deployments:create-project', {
328
+ data: t.Object({
329
+ ...PROJECT_FIELD,
330
+ accountId: t.String({ minLength: 1 }),
331
+ name: t.String({ minLength: 1, maxLength: 100 }),
332
+ gitRepo: t.Optional(t.Union([t.String(), t.Null()])),
333
+ gitProvider: t.Optional(t.Union([t.String(), t.Null()])),
334
+ framework: t.Optional(t.Union([t.String(), t.Null()]))
335
+ }),
336
+ response: DEPLOY_TARGET_SCHEMA
337
+ }, async ({ data, conn }) => {
338
+ const { projectId, project } = resolveDeployProject(conn, data.projectId);
339
+
340
+ debug.log('deployments', `${ws.getUserId(conn)} created a deploy project for ${project.name}`);
341
+
342
+ const target = await deployService.createProject(projectId, data.accountId, {
343
+ name: data.name,
344
+ gitRepo: data.gitRepo ?? null,
345
+ gitProvider: data.gitProvider ?? null,
346
+ framework: data.framework ?? null
347
+ });
348
+ announceDeploymentsChanged(projectId);
349
+ return target;
350
+ })
351
+
352
+ .emit('deployments:log-chunk', t.Object({
353
+ streamId: t.String(),
354
+ deploymentId: t.String(),
355
+ data: t.String(),
356
+ /** Stage the provider reports, pushed the moment it changes. */
357
+ phase: t.Optional(t.String()),
358
+ done: t.Optional(t.Boolean()),
359
+ error: t.Optional(t.Union([t.String(), t.Null()]))
360
+ }));
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Which project a deployments route acts on.
3
+ *
4
+ * The surface lives in More Tools, and More Tools is global — a user looking at
5
+ * project A should be able to watch project B's build without leaving their
6
+ * session. So every route takes an OPTIONAL `projectId` and falls back to the
7
+ * connection's current one, rather than reading the connection and nothing else.
8
+ *
9
+ * Access is still checked per call. `projectId` arriving from the client is a
10
+ * request, not a permission: `requireProjectAccess` is what decides.
11
+ *
12
+ * Unlike the Issues surface this never resolves a worktree. A binding belongs
13
+ * to the project, detection reads the project's own `.vercel/project.json` and
14
+ * git remotes, and a worktree is a copy that carries both — so resolving one
15
+ * would add a failure mode (a tree that was just deleted) and buy nothing.
16
+ */
17
+
18
+ import type { WSConnection } from '$shared/utils/ws-server';
19
+ import type { Project } from '$shared/types/database/schema';
20
+ import { ws } from '$backend/utils/ws';
21
+ import { requireProjectAccess } from '../access';
22
+
23
+ export interface DeployProjectContext {
24
+ projectId: string;
25
+ project: Project;
26
+ /** The tree detection reads from. Always the project root. */
27
+ root: string;
28
+ /** True when this is the project the user is currently working in. */
29
+ isCurrent: boolean;
30
+ }
31
+
32
+ export function resolveDeployProject(conn: WSConnection, projectId?: string): DeployProjectContext {
33
+ const current = ws.getProjectId(conn);
34
+ const target = (projectId ?? '').trim() || current;
35
+ const project = requireProjectAccess(conn, target);
36
+
37
+ return {
38
+ projectId: target,
39
+ project,
40
+ root: project.path,
41
+ isCurrent: target === current
42
+ };
43
+ }