@myrialabs/clopen 0.4.37 → 0.4.38

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 (101) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/http/integration-hooks.ts +42 -0
  28. package/backend/http/notes-images.test.ts +228 -0
  29. package/backend/http/notes-images.ts +196 -0
  30. package/backend/index.ts +9 -0
  31. package/backend/integrations/accounts.ts +229 -0
  32. package/backend/integrations/health.ts +146 -0
  33. package/backend/integrations/index.ts +36 -0
  34. package/backend/integrations/projections/index.ts +120 -0
  35. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  36. package/backend/integrations/projections/mcp-projector.ts +159 -0
  37. package/backend/integrations/projections/types.ts +51 -0
  38. package/backend/integrations/registry/define.ts +38 -0
  39. package/backend/integrations/registry/index.ts +56 -0
  40. package/backend/integrations/registry/providers/context7.ts +44 -0
  41. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  42. package/backend/integrations/registry/providers/github.ts +78 -0
  43. package/backend/integrations/registry/types.ts +96 -0
  44. package/backend/integrations/webhooks/gateway.ts +160 -0
  45. package/backend/integrations/webhooks/verify.ts +65 -0
  46. package/backend/mcp/README.md +25 -3
  47. package/backend/mcp/external/config.ts +35 -1
  48. package/backend/mcp/index.ts +1 -1
  49. package/backend/mcp/internal/config.ts +1 -1
  50. package/backend/notes/access.test.ts +82 -0
  51. package/backend/notes/access.ts +27 -0
  52. package/backend/notes/storage.test.ts +77 -0
  53. package/backend/notes/storage.ts +114 -0
  54. package/backend/permissions/service.ts +2 -2
  55. package/backend/profiles/service.ts +1 -1
  56. package/backend/projects/project-cleanup.ts +6 -0
  57. package/backend/work/bindings.ts +124 -0
  58. package/backend/work/index.ts +42 -0
  59. package/backend/work/prompts.ts +150 -0
  60. package/backend/work/providers/github/actions-logs.ts +180 -0
  61. package/backend/work/providers/github/adapter.test.ts +88 -0
  62. package/backend/work/providers/github/adapter.ts +1255 -0
  63. package/backend/work/providers/github/client.ts +280 -0
  64. package/backend/work/providers/github/list-range.test.ts +158 -0
  65. package/backend/work/providers/github/token-kind.test.ts +42 -0
  66. package/backend/work/pull-requests.ts +242 -0
  67. package/backend/work/registry.ts +27 -0
  68. package/backend/work/service.ts +436 -0
  69. package/backend/work/start-work.test.ts +71 -0
  70. package/backend/work/start-work.ts +232 -0
  71. package/backend/work/types.ts +180 -0
  72. package/backend/ws/files/clipboard.ts +78 -0
  73. package/backend/ws/files/index.ts +5 -0
  74. package/backend/ws/git/diff-budget.ts +70 -11
  75. package/backend/ws/index.ts +11 -1
  76. package/backend/ws/integrations/crud.ts +219 -0
  77. package/backend/ws/integrations/index.ts +22 -0
  78. package/backend/ws/mcp/crud.ts +25 -1
  79. package/backend/ws/notes/index.ts +278 -0
  80. package/backend/ws/profiles/crud.ts +1 -1
  81. package/backend/ws/work/actions.ts +206 -0
  82. package/backend/ws/work/context.ts +51 -0
  83. package/backend/ws/work/crud.ts +347 -0
  84. package/backend/ws/work/index.ts +17 -0
  85. package/backend/ws/work/pull-requests.ts +177 -0
  86. package/backend/ws/work/schemas.ts +226 -0
  87. package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
  88. package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
  89. package/dist/assets/main-D2IOjftb.css +1 -0
  90. package/dist/assets/main-DM-tHKbW.js +1152 -0
  91. package/dist/index.html +2 -2
  92. package/package.json +1 -1
  93. package/shared/constants/engine-tools.ts +1 -1
  94. package/shared/constants/tool-icons.ts +33 -0
  95. package/shared/types/database/schema.ts +41 -0
  96. package/shared/types/integrations.ts +140 -0
  97. package/shared/types/stores/settings.ts +8 -0
  98. package/shared/types/work.ts +426 -0
  99. package/shared/utils/logger.ts +3 -0
  100. package/dist/assets/main-DLqolBI2.css +0 -1
  101. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Branch naming for "start work".
3
+ *
4
+ * This is the piece of the flow with no network and no database, and it is also
5
+ * the piece that produces a value git either accepts or refuses. A template that
6
+ * renders to something git rejects turns the whole action into a worktree on a
7
+ * detached HEAD, so the cases below are the ones that would produce a bad ref.
8
+ */
9
+
10
+ import { describe, it, expect } from 'bun:test';
11
+
12
+ import { renderBranchName } from './start-work';
13
+ import { DEFAULT_BRANCH_TEMPLATE } from '$shared/types/work';
14
+
15
+ const issue = (title: string, identifier = '123') => ({
16
+ kind: 'issue' as const,
17
+ identifier,
18
+ title
19
+ });
20
+
21
+ describe('renderBranchName', () => {
22
+ it('fills the default template', () => {
23
+ expect(renderBranchName(DEFAULT_BRANCH_TEMPLATE, issue('Sessions drop on reconnect')))
24
+ .toBe('issue/123-sessions-drop-on-reconnect');
25
+ });
26
+
27
+ it('calls a pull request pr, not pull-request', () => {
28
+ expect(
29
+ renderBranchName(DEFAULT_BRANCH_TEMPLATE, {
30
+ kind: 'pull-request',
31
+ identifier: '9',
32
+ title: 'Retry the handshake'
33
+ })
34
+ ).toBe('pr/9-retry-the-handshake');
35
+ });
36
+
37
+ it('strips characters git refuses in a ref name', () => {
38
+ // Spaces, `~`, `^`, `:` and `..` are all rejected by git; the slug reduces
39
+ // to [a-z0-9-], which is a strict subset of what it accepts.
40
+ const branch = renderBranchName(DEFAULT_BRANCH_TEMPLATE, issue('Fix: crash on ~/.. paths ^HEAD'));
41
+ expect(branch).toMatch(/^issue\/123-[a-z0-9-]+$/);
42
+ expect(branch).not.toContain('..');
43
+ });
44
+
45
+ it('keeps a non-numeric identifier like a tracker key', () => {
46
+ expect(renderBranchName(DEFAULT_BRANCH_TEMPLATE, issue('Add audit log', 'ENG-45')))
47
+ .toBe('issue/eng-45-add-audit-log');
48
+ });
49
+
50
+ it('never emits a trailing separator when the title slugifies to nothing', () => {
51
+ const branch = renderBranchName(DEFAULT_BRANCH_TEMPLATE, issue('!!! ???'));
52
+ expect(branch).toBe('issue/123');
53
+ expect(branch.endsWith('-')).toBe(false);
54
+ expect(branch.endsWith('/')).toBe(false);
55
+ });
56
+
57
+ it('falls back rather than returning an empty ref', () => {
58
+ // `git checkout -b ""` is the failure this guards: a template of only
59
+ // `{slug}` against an unslugifiable title renders to nothing.
60
+ expect(renderBranchName('{slug}', issue('———'))).toBe('work/123');
61
+ });
62
+
63
+ it('honours a custom template', () => {
64
+ expect(renderBranchName('feat/{identifier}', issue('Anything'))).toBe('feat/123');
65
+ });
66
+
67
+ it('collapses repeated separators left by an empty placeholder', () => {
68
+ expect(renderBranchName('{kind}/{slug}--{identifier}', issue('Cache miss')))
69
+ .toBe('issue/cache-miss-123');
70
+ });
71
+ });
@@ -0,0 +1,232 @@
1
+ /**
2
+ * "Start work" — from a work item to an agent that is already working.
3
+ *
4
+ * Four things happen, in an order chosen so a failure never leaves a mess:
5
+ *
6
+ * 1. Read the item (body + comments) while nothing has been created yet, so a
7
+ * provider outage costs nothing.
8
+ * 2. Create the worktree — the expensive, visible step.
9
+ * 3. Create the branch inside it. Best effort: a project that is not a git
10
+ * repository, or one whose branch name is already taken, still gets a
11
+ * worktree and a session. Losing the whole action over a branch name would
12
+ * be a poor trade.
13
+ * 4. Create the session, record the link, and compose the first message.
14
+ *
15
+ * The state transition runs last and NEVER fails the action. Moving a ticket is
16
+ * a courtesy; the worktree and the session are the thing the user asked for, and
17
+ * throwing away both because a label change was rejected would be absurd.
18
+ */
19
+
20
+ import { sessionQueries, workLinkQueries } from '$backend/database/queries';
21
+ import { gitService } from '$backend/git/git-service';
22
+ import { createWorktree } from '$backend/worktrees';
23
+ import type { EngineType } from '$shared/types/unified';
24
+ import type { StartWorkResult, WorkItemDetail, WorkItemKind } from '$shared/types/work';
25
+ import { workService } from './service';
26
+ import { buildStartWorkPrompt } from './prompts';
27
+ import { debug } from '$shared/utils/logger';
28
+
29
+ /** Worktree names are capped at 80 by the create route; leave room for the id. */
30
+ const MAX_WORKTREE_NAME = 60;
31
+
32
+ /**
33
+ * A branch-safe slug.
34
+ *
35
+ * git refuses a lot of things in a ref name — spaces, `..`, `~`, `^`, `:`, a
36
+ * trailing dot, a leading dash. Rather than encode that rule set, this reduces
37
+ * to `[a-z0-9-]`, which is a strict subset of what git allows and also survives
38
+ * being a directory name on Windows.
39
+ */
40
+ function slugify(text: string, maxWords = 6): string {
41
+ return text
42
+ .toLowerCase()
43
+ .normalize('NFKD')
44
+ .replace(/[^\w\s-]/g, ' ')
45
+ .trim()
46
+ .split(/[\s_-]+/)
47
+ .filter(Boolean)
48
+ .slice(0, maxWords)
49
+ .join('-')
50
+ .slice(0, 50)
51
+ .replace(/^-+|-+$/g, '');
52
+ }
53
+
54
+ /** Fill the binding's branch template. Unknown placeholders are left alone. */
55
+ export function renderBranchName(template: string, item: { kind: WorkItemKind; identifier: string; title: string }): string {
56
+ const slug = slugify(item.title);
57
+ const rendered = template
58
+ .replace(/\{kind\}/g, item.kind === 'pull-request' ? 'pr' : 'issue')
59
+ .replace(/\{identifier\}/g, slugify(item.identifier, 3) || item.identifier)
60
+ .replace(/\{slug\}/g, slug)
61
+ .replace(/\/{2,}/g, '/')
62
+ .replace(/-{2,}/g, '-')
63
+ .replace(/[-/]+$/g, '');
64
+
65
+ // A template that rendered to nothing (an item with an unslugifiable title
66
+ // and a template of only `{slug}`) would produce `git checkout -b ""`.
67
+ return rendered || `work/${item.identifier}`;
68
+ }
69
+
70
+ function worktreeNameFor(item: { identifier: string; title: string }): string {
71
+ const name = `#${item.identifier} ${item.title}`.trim();
72
+ return name.length > MAX_WORKTREE_NAME ? `${name.slice(0, MAX_WORKTREE_NAME - 1)}…` : name;
73
+ }
74
+
75
+ export async function startWork(input: {
76
+ projectId: string;
77
+ accountId: string;
78
+ kind: WorkItemKind;
79
+ itemId: string;
80
+ engine: EngineType;
81
+ userId: string;
82
+ }): Promise<StartWorkResult> {
83
+ const { adapter, context } = workService.require(input.projectId, input.accountId);
84
+
85
+ const item: WorkItemDetail = await adapter.get(context, input.kind, input.itemId);
86
+
87
+ // Starting work on a PULL REQUEST means reviewing code that already exists,
88
+ // so the branch is checked out rather than invented. Starting work on an
89
+ // ISSUE means writing code that does not, so a branch is created from the
90
+ // template. Getting this backwards would drop someone into an empty branch
91
+ // and ask them to review it.
92
+ const plan: BranchPlan = item.kind === 'pull-request' && item.headBranch
93
+ ? { mode: 'checkout', name: item.headBranch }
94
+ : { mode: 'create', name: renderBranchName(context.binding.config.branchTemplate, item) };
95
+
96
+ const worktree = await createWorktree({
97
+ projectId: input.projectId,
98
+ name: worktreeNameFor(item),
99
+ createdBy: input.userId
100
+ });
101
+
102
+ const branch = await applyBranchPlan(worktree.worktree.path, plan);
103
+
104
+ const session = sessionQueries.create({
105
+ project_id: input.projectId,
106
+ title: worktreeNameFor(item),
107
+ engine: input.engine,
108
+ started_at: new Date().toISOString(),
109
+ worktree_id: worktree.worktree.id
110
+ });
111
+
112
+ workLinkQueries.upsert({
113
+ projectId: input.projectId,
114
+ accountId: input.accountId,
115
+ itemKind: input.kind,
116
+ itemIdentifier: item.identifier,
117
+ itemTitle: item.title,
118
+ itemUrl: item.url,
119
+ worktreeId: worktree.worktree.id,
120
+ sessionId: session.id,
121
+ branch
122
+ });
123
+
124
+ const transition = await applyTransition(
125
+ context.binding.config.transitionOnStartWork,
126
+ input,
127
+ item.kind,
128
+ item.id
129
+ );
130
+
131
+ return {
132
+ worktreeId: worktree.worktree.id,
133
+ worktreeName: worktree.worktree.name,
134
+ sessionId: session.id,
135
+ branch,
136
+ prompt: buildStartWorkPrompt(item, {
137
+ branch,
138
+ branchMode: plan.mode,
139
+ locator: adapter.describeLocator(context.binding.locator)
140
+ }),
141
+ transitionedTo: transition.applied,
142
+ transitionError: transition.error,
143
+ needsSetup: !worktree.carriedIgnoredFiles
144
+ };
145
+ }
146
+
147
+ interface BranchPlan {
148
+ /** `create` invents a branch; `checkout` moves onto one that already exists. */
149
+ mode: 'create' | 'checkout';
150
+ name: string;
151
+ }
152
+
153
+ /**
154
+ * Put the new worktree on the right branch, best effort.
155
+ *
156
+ * Every failure here degrades to "the worktree is on whatever branch it cloned
157
+ * with", which is still a usable session. Losing the worktree, the session and
158
+ * the prompt because a branch name was taken would be a much worse trade — and
159
+ * a project that is not a git repository at all still deserves the session.
160
+ */
161
+ async function applyBranchPlan(cwd: string, plan: BranchPlan): Promise<string> {
162
+ try {
163
+ if (plan.mode === 'create') {
164
+ await gitService.createBranch(cwd, plan.name);
165
+ return plan.name;
166
+ }
167
+
168
+ // The pull request's branch may exist locally, may only exist on the
169
+ // remote, or may not have been fetched into this clone yet — so fetch
170
+ // first, try the local checkout, and fall back to branching off the
171
+ // remote-tracking ref.
172
+ await gitService.fetch(cwd, 'origin').catch(() => '');
173
+ try {
174
+ await gitService.switchBranch(cwd, plan.name);
175
+ } catch {
176
+ await gitService.createBranch(cwd, plan.name, `origin/${plan.name}`);
177
+ }
178
+ return plan.name;
179
+ } catch (error) {
180
+ debug.warn('work', `Could not put the worktree on "${plan.name}":`, error);
181
+ // Report the branch the work is actually on, not the one we wanted: a PR
182
+ // composer prefilled with a branch that does not exist is worse than one
183
+ // that has to ask.
184
+ return currentBranch(cwd);
185
+ }
186
+ }
187
+
188
+ /** The branch the worktree ended up on, or a readable placeholder. */
189
+ async function currentBranch(cwd: string): Promise<string> {
190
+ try {
191
+ const info = await gitService.getBranches(cwd);
192
+ return info.current || 'HEAD';
193
+ } catch {
194
+ return 'HEAD';
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Apply a configured transition, reporting rather than throwing.
200
+ *
201
+ * Both outcomes are returned so the UI can be honest: "moved to In Progress" and
202
+ * "could not move it — you are not a collaborator" are different messages, and
203
+ * silence would be worse than either.
204
+ */
205
+ async function applyTransition(
206
+ state: string | null,
207
+ input: { projectId: string; accountId: string },
208
+ kind: WorkItemKind,
209
+ itemId: string
210
+ ): Promise<{ applied: string | null; error: string | null }> {
211
+ if (!state) return { applied: null, error: null };
212
+
213
+ try {
214
+ await workService.transition(input.projectId, input.accountId, kind, itemId, state);
215
+ return { applied: state, error: null };
216
+ } catch (error) {
217
+ const detail = error instanceof Error ? error.message : String(error);
218
+ debug.warn('work', `Configured transition to "${state}" failed:`, error);
219
+ return { applied: null, error: detail };
220
+ }
221
+ }
222
+
223
+ /** Exported for the PR flow, which applies its own configured transition. */
224
+ export async function applyConfiguredTransition(
225
+ projectId: string,
226
+ accountId: string,
227
+ kind: WorkItemKind,
228
+ itemId: string,
229
+ state: string | null
230
+ ): Promise<{ applied: string | null; error: string | null }> {
231
+ return applyTransition(state, { projectId, accountId }, kind, itemId);
232
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Issue-provider adapter contract.
3
+ *
4
+ * This is the interface `Task 2` exists to build. GitHub is the first provider
5
+ * behind it, and GitLab, Gitea, Forgejo, Linear, Jira and PostHog are meant to
6
+ * land as another file in `providers/` and one line in the registry. If any of
7
+ * them needs a change to the PANEL, this interface is what was wrong.
8
+ *
9
+ * Note what this is NOT: a projector. A projection derives a row on a surface
10
+ * that already has its own table — `mcp_servers` for agent tools,
11
+ * `db_client_connections` for a database. The Issues & PRs surface has no such table
12
+ * to write into, because work items are never copied locally (see migration
13
+ * 074). So an issue provider registers CODE here, and the account row itself is
14
+ * what makes it appear in the panel.
15
+ */
16
+
17
+ import type {
18
+ CheckLogBundle,
19
+ CheckRun,
20
+ CommentSource,
21
+ CommitDetail,
22
+ CommitRef,
23
+ FileContent,
24
+ FileChange,
25
+ WorkBindingConfig,
26
+ WorkProviderCapabilities,
27
+ MergeMethod,
28
+ PullRequestDraft,
29
+ WorkItem,
30
+ WorkItemComment,
31
+ WorkItemDetail,
32
+ WorkItemKind,
33
+ WorkItemPage,
34
+ WorkItemQuery,
35
+ WorkItemStateOption
36
+ } from '$shared/types/work';
37
+ import type { IntegrationAccountRow } from '$backend/database/queries';
38
+
39
+ /** The remote project one account is pointed at, for one Clopen project. */
40
+ export interface ResolvedBinding {
41
+ locator: string;
42
+ detected: boolean;
43
+ defaultBranch: string | null;
44
+ config: WorkBindingConfig;
45
+ }
46
+
47
+ /**
48
+ * Everything an adapter call needs.
49
+ *
50
+ * `credentials` is already decoded. It is assembled by the service from the
51
+ * account row and never leaves the backend — no route serialises it, and the
52
+ * adapter must not put it anywhere a `WorkItem` can carry it back out.
53
+ */
54
+ export interface WorkContext {
55
+ projectId: string;
56
+ account: IntegrationAccountRow;
57
+ credentials: Record<string, string>;
58
+ binding: ResolvedBinding;
59
+ }
60
+
61
+ /** Same, before a binding exists — the only calls that can run unbound. */
62
+ export interface UnboundContext {
63
+ projectId: string;
64
+ account: IntegrationAccountRow;
65
+ credentials: Record<string, string>;
66
+ }
67
+
68
+ export interface WorkProviderAdapter {
69
+ /** Must match the `IntegrationProvider.id` this adapter serves. */
70
+ provider: string;
71
+ capabilities: WorkProviderCapabilities;
72
+
73
+ /**
74
+ * Turn a git remote URL into a locator, or null when it belongs to someone
75
+ * else. This is what makes binding automatic: the panel asks every adapter
76
+ * about every remote and keeps the answers that are not null.
77
+ *
78
+ * A self-hosted provider decides using the account's configured base URL,
79
+ * which is why the credentials are passed in rather than just the URL.
80
+ */
81
+ locatorFromRemote(url: string, credentials: Record<string, string>): string | null;
82
+
83
+ /** Human form of a locator, for the binding bar. */
84
+ describeLocator(locator: string): string;
85
+
86
+ /**
87
+ * Is this credential good, and does it reach the bound project?
88
+ *
89
+ * Runs at connect time and from the hub's health button. A token that is
90
+ * valid but lacks a permission must fail HERE, with the missing permission
91
+ * named — not three clicks later as a 403 from an unrelated action.
92
+ */
93
+ probe(context: UnboundContext, binding: ResolvedBinding | null): Promise<{
94
+ status: 'ok' | 'needs_auth' | 'needs_config' | 'error';
95
+ detail: string | null;
96
+ }>;
97
+
98
+ /** States an item of this kind can be moved to. */
99
+ listStates(context: WorkContext, kind: WorkItemKind): Promise<WorkItemStateOption[]>;
100
+
101
+ list(context: WorkContext, query: WorkItemQuery): Promise<WorkItemPage>;
102
+ get(context: WorkContext, kind: WorkItemKind, id: string): Promise<WorkItemDetail>;
103
+ comment(context: WorkContext, kind: WorkItemKind, id: string, body: string): Promise<WorkItemComment>;
104
+ transition(context: WorkContext, kind: WorkItemKind, id: string, state: string): Promise<void>;
105
+
106
+ /** The branch a PR should target by default. Cached on the binding. */
107
+ defaultBranch(context: WorkContext): Promise<string>;
108
+
109
+ /** CI runs for a branch. Absent when the provider has no CI to speak of. */
110
+ listChecks?(context: WorkContext, branch: string): Promise<CheckRun[]>;
111
+ /** Logs for one run, already trimmed to a size a prompt can carry. */
112
+ fetchCheckLogs?(context: WorkContext, runId: string): Promise<CheckLogBundle>;
113
+
114
+ createPullRequest?(context: WorkContext, draft: PullRequestDraft): Promise<WorkItem>;
115
+ /** An open PR whose head is this branch, when there is one. */
116
+ findPullRequestForBranch?(context: WorkContext, branch: string): Promise<WorkItem | null>;
117
+
118
+ /** Who the stored credential belongs to. Decides what the user may edit. */
119
+ viewer?(context: UnboundContext): Promise<string | null>;
120
+
121
+ /** Change an item's title, body, or both. */
122
+ updateItem?(
123
+ context: WorkContext,
124
+ kind: WorkItemKind,
125
+ id: string,
126
+ patch: { title?: string; body?: string }
127
+ ): Promise<void>;
128
+ /** Labels this repository defines, for the filter panel. */
129
+ listLabels?(context: WorkContext): Promise<string[]>;
130
+
131
+ /**
132
+ * Editing and deleting a comment.
133
+ *
134
+ * `source` travels because a provider may keep review comments on a
135
+ * different endpoint from the discussion thread — GitHub does, and using the
136
+ * wrong one is a 404 rather than a permission error.
137
+ */
138
+ updateComment?(
139
+ context: WorkContext,
140
+ comment: { id: string; source: CommentSource },
141
+ body: string
142
+ ): Promise<WorkItemComment>;
143
+ deleteComment?(
144
+ context: WorkContext,
145
+ comment: { id: string; source: CommentSource }
146
+ ): Promise<void>;
147
+
148
+ /** Merge a pull request. Outward-facing: the caller confirms first. */
149
+ mergePullRequest?(
150
+ context: WorkContext,
151
+ id: string,
152
+ options: { method: MergeMethod; title?: string; message?: string }
153
+ ): Promise<void>;
154
+
155
+ listCommits?(context: WorkContext, id: string): Promise<CommitRef[]>;
156
+ /** One commit's message, stats and files — what a list row cannot carry. */
157
+ commitDetail?(context: WorkContext, sha: string): Promise<CommitDetail>;
158
+ /**
159
+ * One file's full text, for the in-app viewer.
160
+ *
161
+ * `blobSha` is the preferred address when the caller has one; `ref` is the
162
+ * fallback for providers or call sites that only know a branch.
163
+ */
164
+ fetchFileContent?(
165
+ context: WorkContext,
166
+ path: string,
167
+ ref: string,
168
+ blobSha?: string
169
+ ): Promise<FileContent>;
170
+ listFiles?(context: WorkContext, id: string): Promise<FileChange[]>;
171
+
172
+ /** People this item can be assigned to. */
173
+ listAssignees?(context: WorkContext): Promise<string[]>;
174
+ setAssignees?(context: WorkContext, kind: WorkItemKind, id: string, logins: string[]): Promise<void>;
175
+
176
+ createIssue?(
177
+ context: WorkContext,
178
+ draft: { title: string; body: string; assignees: string[]; labels: string[] }
179
+ ): Promise<WorkItem>;
180
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Files OS Clipboard Operations
3
+ *
4
+ * `files:copy-to-os-clipboard` — places Clopen files/folders onto the native
5
+ * clipboard of the machine the SERVER runs on, so the user can paste them in
6
+ * File Explorer / Finder / their Linux file manager. `effect: 'copy'`
7
+ * (default) pastes duplicates and keeps the Clopen sources; `effect: 'move'`
8
+ * (used for CUT) lets the file manager relocate them. The response echoes the
9
+ * effect that was actually published — macOS cannot express "move" on the
10
+ * pasteboard, so a CUT lands there as a copy and the UI says so. The
11
+ * frontend's internal clipboard is untouched; this only adds the OS-native
12
+ * side.
13
+ *
14
+ * `files:read-os-clipboard` — the reverse direction: reads file/folder
15
+ * entries copied in a native file manager so the Clopen context-menu Paste
16
+ * works even when the copy source was outside Clopen. Browsers cannot read a
17
+ * native file-drop list on a menu click (no DataTransfer), hence this backend
18
+ * round-trip.
19
+ *
20
+ * Security: both routes act on the HOST machine's clipboard, which belongs to
21
+ * whoever runs the server — not to a remote collaborator. A member's project
22
+ * grants say nothing about that clipboard, and its contents are absolute
23
+ * paths that can sit anywhere on disk (another user's project, a home
24
+ * directory), so both routes are admin-only.
25
+ *
26
+ * The read route answers a non-admin with an empty list rather than an error:
27
+ * the frontend polls it to decide whether to offer "Paste", and an empty list
28
+ * simply means "nothing pasteable from the OS" — no error toast on every
29
+ * context-menu open. The write route throws, because it is only ever reached
30
+ * from an explicit Copy/Cut the caller asked for.
31
+ *
32
+ * Published paths still go through the standard per-user file access guard on
33
+ * top of the admin check, so the guard stays correct if the policy is ever
34
+ * widened. The backend only *publishes references* — the file manager
35
+ * performs the actual copy, and sources are never moved or deleted by Clopen.
36
+ */
37
+
38
+ import { t } from 'elysia';
39
+ import { createRouter } from '$shared/utils/ws-server';
40
+ import { ws } from '$backend/utils/ws';
41
+ import { copyPathsToOsClipboard, readOsClipboardFilePaths } from '../../files/os-clipboard';
42
+ import { requireFilePathAccess } from './path-access';
43
+
44
+ export const clipboardHandler = createRouter()
45
+ .http('files:copy-to-os-clipboard', {
46
+ data: t.Object({
47
+ paths: t.Array(t.String(), { minItems: 1 }),
48
+ effect: t.Optional(t.Union([t.Literal('copy'), t.Literal('move')]))
49
+ }),
50
+ response: t.Object({
51
+ count: t.Number(),
52
+ /** The effect actually published — `copy` on macOS even for a CUT. */
53
+ effect: t.Union([t.Literal('copy'), t.Literal('move')])
54
+ })
55
+ }, async ({ data, conn }) => {
56
+ if (ws.getRole(conn) !== 'admin') {
57
+ throw new Error('Access denied');
58
+ }
59
+ const resolved: string[] = [];
60
+ for (const p of data.paths) {
61
+ resolved.push(await requireFilePathAccess(conn, p));
62
+ }
63
+ return await copyPathsToOsClipboard(resolved, data.effect ?? 'copy');
64
+ })
65
+ .http('files:read-os-clipboard', {
66
+ data: t.Object({}),
67
+ response: t.Object({
68
+ items: t.Array(t.Object({
69
+ path: t.String(),
70
+ isDirectory: t.Boolean()
71
+ }))
72
+ })
73
+ }, async ({ conn }) => {
74
+ if (ws.getRole(conn) !== 'admin') {
75
+ return { items: [] };
76
+ }
77
+ return { items: await readOsClipboardFilePaths() };
78
+ });
@@ -7,6 +7,7 @@
7
7
  * - read.ts: HTTP endpoints for reading (list-tree, browse, read-file, read-content)
8
8
  * - write.ts: HTTP endpoints for writing (write, create, rename, duplicate, upload, delete)
9
9
  * - reveal.ts: HTTP endpoint for revealing files in the OS file manager
10
+ * - clipboard.ts: HTTP endpoints for the native OS clipboard bridge (admin-only)
10
11
  * - search.ts: HTTP endpoints for searching (search-files, search-code)
11
12
  * - watch.ts: Event handlers for real-time file watching
12
13
  */
@@ -15,6 +16,7 @@ import { createRouter } from '$shared/utils/ws-server';
15
16
  import { readHandler } from './read';
16
17
  import { writeHandler } from './write';
17
18
  import { revealHandler } from './reveal';
19
+ import { clipboardHandler } from './clipboard';
18
20
  import { imageEditHandler } from './image-edit';
19
21
  import { fileSearchHandler } from './search';
20
22
  import { watchHandler } from './watch';
@@ -30,6 +32,9 @@ export const filesRouter = createRouter()
30
32
  // Reveal in File Manager (HTTP)
31
33
  .merge(revealHandler)
32
34
 
35
+ // OS Clipboard bridge — read/write native file-drop lists (HTTP)
36
+ .merge(clipboardHandler)
37
+
33
38
  // Image Edit Operation (HTTP)
34
39
  .merge(imageEditHandler)
35
40