clay-server 5.6.0 → 5.7.0-beta.2

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 (80) hide show
  1. package/README.md +4 -0
  2. package/bin/cli.js +2 -0
  3. package/lib/clay-product-control.js +2 -1
  4. package/lib/cli-project-recovery.js +22 -0
  5. package/lib/daemon.js +14 -0
  6. package/lib/mcp-agent-management.js +98 -0
  7. package/lib/mcp-agent-tools.js +4 -3
  8. package/lib/mcp-local-configuration.js +20 -0
  9. package/lib/mcp-management-service.js +96 -0
  10. package/lib/mcp-remote-connections.js +127 -35
  11. package/lib/mcp-settings-navigation.js +34 -0
  12. package/lib/mcp-xcode.js +43 -0
  13. package/lib/project-admin-overview.js +4 -4
  14. package/lib/project-mcp.js +28 -6
  15. package/lib/project-ownership-diagnostics.js +37 -0
  16. package/lib/project-ownership-recovery.js +61 -0
  17. package/lib/project-ownership.js +1 -34
  18. package/lib/project-recovery-approvals.js +38 -0
  19. package/lib/public/app.js +4 -0
  20. package/lib/public/css/mcp-connections.css +15 -0
  21. package/lib/public/css/mcp-skills-workbench.css +6 -4
  22. package/lib/public/css/project-admin-overview.css +13 -0
  23. package/lib/public/css/project-settings-modal.css +13 -0
  24. package/lib/public/css/settings-shell.css +42 -0
  25. package/lib/public/index.html +4 -4
  26. package/lib/public/modules/clay-tool-presentation.js +7 -0
  27. package/lib/public/modules/extension-settings.js +1 -1
  28. package/lib/public/modules/mcp-connection-view.js +52 -24
  29. package/lib/public/modules/mcp-skills-workbench.js +10 -3
  30. package/lib/public/modules/mcp-ui.js +40 -11
  31. package/lib/public/modules/mcp-xcode-view.js +42 -0
  32. package/lib/public/modules/project-admin-overview.js +15 -0
  33. package/lib/public/modules/project-ownership-recovery.js +75 -0
  34. package/lib/public/modules/project-session-visibility-settings.js +1 -1
  35. package/lib/public/modules/project-settings-access.js +91 -0
  36. package/lib/public/modules/project-settings-environment.js +3 -2
  37. package/lib/public/modules/project-settings.js +39 -5
  38. package/lib/public/modules/projects-hub.js +3 -3
  39. package/lib/public/modules/settings-project-tree.js +74 -0
  40. package/lib/public/modules/settings-shell-view.js +3 -1
  41. package/lib/public/modules/settings-shell.js +3 -2
  42. package/lib/public/pane-assets/app-NNFRGDUF.js +1 -0
  43. package/lib/public/pane-assets/{chunk-WI7YYJ5R.js → chunk-2TORIX6C.js} +1 -1
  44. package/lib/public/pane-assets/chunk-4Z62BYOI.js +1 -0
  45. package/lib/public/pane-assets/{chunk-TKD25TLY.js → chunk-55VDDGEC.js} +1 -1
  46. package/lib/public/pane-assets/{chunk-HXD34AZT.js → chunk-5FFTX7ZC.js} +1 -1
  47. package/lib/public/pane-assets/{chunk-IIZZTDLB.js → chunk-7EUVDTMT.js} +1 -1
  48. package/lib/public/pane-assets/{chunk-K3AFWB4T.js → chunk-AB5DMBJP.js} +101 -101
  49. package/lib/public/pane-assets/{chunk-4KCNVBBD.js → chunk-BV7EM5FS.js} +1 -1
  50. package/lib/public/pane-assets/{chunk-OHKQX2VV.js → chunk-CVBBTNG6.js} +1 -1
  51. package/lib/public/pane-assets/{chunk-YDQZXMHJ.js → chunk-DF46TE6L.js} +1 -1
  52. package/lib/public/pane-assets/{chunk-H3BOT3SB.js → chunk-G7KDNICR.js} +1 -1
  53. package/lib/public/pane-assets/chunk-J5NQRVK2.js +1 -0
  54. package/lib/public/pane-assets/{chunk-25X3V6RW.js → chunk-JFGW235Q.js} +1 -1
  55. package/lib/public/pane-assets/chunk-KV2DOKIE.js +1 -0
  56. package/lib/public/pane-assets/{chunk-TUZOISN6.js → chunk-KXPI3AAA.js} +1 -1
  57. package/lib/public/pane-assets/{chunk-I5RM7KNO.js → chunk-NEOF2E22.js} +1 -1
  58. package/lib/public/pane-assets/chunk-OSHUOAE5.js +1 -0
  59. package/lib/public/pane-assets/chunk-OX6UEH75.js +1 -0
  60. package/lib/public/pane-assets/{chunk-UBGZO6GV.js → chunk-PHID25XP.js} +1 -1
  61. package/lib/public/pane-assets/chunk-QTDFQTIE.js +1 -0
  62. package/lib/public/pane-assets/{chunk-KLRVHJC5.js → chunk-THIXGWT6.js} +1 -1
  63. package/lib/public/pane-assets/chunk-VSP7FSCE.js +1 -0
  64. package/lib/public/pane-assets/chunk-ZEQGT5FY.js +1 -0
  65. package/lib/public/pane-assets/{chunk-H6RI6IG5.js → chunk-ZEV2KT7L.js} +1 -1
  66. package/lib/public/pane-assets/manifest.json +430 -426
  67. package/lib/public/pane-assets/style-IPMITHXL.css +1 -0
  68. package/lib/server-project-ownership.js +43 -0
  69. package/lib/server.js +5 -0
  70. package/package.json +1 -1
  71. package/lib/public/pane-assets/app-QR6W64PK.js +0 -1
  72. package/lib/public/pane-assets/chunk-AKFJO7SA.js +0 -1
  73. package/lib/public/pane-assets/chunk-DX7R6GRL.js +0 -1
  74. package/lib/public/pane-assets/chunk-F33TBKP2.js +0 -1
  75. package/lib/public/pane-assets/chunk-PTZ2QTNA.js +0 -1
  76. package/lib/public/pane-assets/chunk-QWNMLSVA.js +0 -1
  77. package/lib/public/pane-assets/chunk-VG32EEIQ.js +0 -1
  78. package/lib/public/pane-assets/chunk-W2W4CPO7.js +0 -1
  79. package/lib/public/pane-assets/chunk-XX2GY7T5.js +0 -1
  80. package/lib/public/pane-assets/style-BCUGGAD3.css +0 -1
@@ -14,11 +14,16 @@ function send(message) {
14
14
  }
15
15
  function requestState() { send({ type: 'mcp_state_request' }); }
16
16
  function clearActionTimer() { var timer = store.get('mcpActionTimer'); if (timer) clearTimeout(timer); store.set({ mcpActionTimer: null }); }
17
- function navigate(screen, id) { patch({ screen: screen, selected: id || null, error: '', notice: '', search: '', detailTab: 'tools' }); }
17
+ function navigate(screen, id) {
18
+ if (screen === 'computer') screen = 'local';
19
+ patch({ screen: screen, selected: id || null, error: '', notice: '', search: '', detailTab: 'tools' });
20
+ if (screen === 'xcode') { requestState(); action('xcode_check'); }
21
+ }
18
22
  function action(name, args) {
19
- if (state().pending) return;
23
+ if (state().pending && name !== 'xcode_disconnect') return;
20
24
  var requestId = crypto.randomUUID();
21
- patch({ pending: { requestId: requestId, action: name }, error: '', notice: '' });
25
+ var tab = (store.get('mcpSkillsWorkbench') || {}).tab || 'mcp';
26
+ patch({ pending: { requestId: requestId, action: name, tab: tab, screen: state().screen }, feedbackTab: tab, error: '', notice: '' });
22
27
  clearActionTimer();
23
28
  store.set({ mcpActionTimer: setTimeout(function () {
24
29
  if (state().pending && state().pending.requestId === requestId) { patch({ pending: null, error: 'The server is taking longer than expected. Refresh connections to check its state.' }); requestState(); }
@@ -28,7 +33,7 @@ function action(name, args) {
28
33
  function discover(options) {
29
34
  if (state().pending) return;
30
35
  var requestId = crypto.randomUUID();
31
- patch({ pending: { requestId: requestId, action: 'discover' }, error: '' });
36
+ patch({ pending: { requestId: requestId, action: 'discover', tab: 'mcp' }, feedbackTab: 'mcp', error: '' });
32
37
  clearActionTimer();
33
38
  store.set({ mcpActionTimer: setTimeout(function () {
34
39
  if (state().pending && state().pending.requestId === requestId) { clearActionTimer(); patch({ pending: null, error: 'The scan did not respond. Your draft and previous results are retained. Reconnect or scan again.' }); }
@@ -36,19 +41,22 @@ function discover(options) {
36
41
  if (!send(Object.assign({ type: 'mcp_discovery_request', requestId: requestId }, options || {}))) { clearActionTimer(); patch({ pending: null }); }
37
42
  }
38
43
  function toggle(row, value) {
39
- if (row.source !== 'computer') action('enable', { id: row.id, enabled: value });
40
- else send({ type: 'mcp_toggle_server', name: row.name, enabled: value });
44
+ if (row.integration === 'xcode' && value) action('xcode_connect');
45
+ else if (row.source !== 'computer') action('enable', { id: row.id, enabled: value });
46
+ else { patch({ feedbackTab: 'mcp', error: '', notice: '' }); send({ type: 'mcp_toggle_server', name: row.name, enabled: value }); }
41
47
  }
42
48
  function render() {
43
49
  var element = document.getElementById('mcp-content');
44
50
  if (!element) return;
45
51
  var current = state();
46
52
  var extension = document.getElementById('ext-pill-wrap');
47
- if (extension) extension.hidden = current.screen !== 'computer';
53
+ if (extension) extension.hidden = current.screen !== 'client';
48
54
  renderConnections(element, current, {
49
55
  navigate: navigate, action: action, toggle: toggle, discover: discover,
56
+ localDraft: function (value) { patch({ localDraft: value }); },
50
57
  sourceDraft: function (value) { patch({ sourceDraft: value }); },
51
58
  search: function (value) { patch({ search: value }); },
59
+ detailTab: function (value) { patch({ detailTab: value, search: '' }); },
52
60
  draft: function (value) { store.set({ mcpConnectionDraft: value }); },
53
61
  refresh: requestState,
54
62
  setup: function () { var button = document.getElementById('ext-pill'); if (button) button.click(); },
@@ -70,20 +78,39 @@ export function initMcp() {
70
78
  }
71
79
  if (current.connected !== previous.connected) {
72
80
  if (current.connected) requestState();
73
- else { clearActionTimer(); patch({ pending: null, error: 'Connection lost. Reconnect to manage your servers.' }); }
81
+ else { clearActionTimer(); patch({ pending: null, feedbackTab: null, error: 'Connection lost. Reconnect to manage your servers.' }); }
74
82
  }
83
+ if (current.mcpSkillsWorkbench !== previous.mcpSkillsWorkbench && current.mcpSkillsWorkbench && current.mcpSkillsWorkbench.open && current.mcpSkillsWorkbench.tab === 'mcp' && state().screen === 'xcode') { requestState(); action('xcode_check'); }
75
84
  if (current.mcpConnections !== previous.mcpConnections || current.mcpSkillsWorkbench !== previous.mcpSkillsWorkbench || current.activeSessionId !== previous.activeSessionId || current.mcpPermissionModeOverrides !== previous.mcpPermissionModeOverrides || current.permissionCapabilities !== previous.permissionCapabilities || current.effectivePermissionMode !== previous.effectivePermissionMode || current.mcpPermissionModePendingByTarget !== previous.mcpPermissionModePendingByTarget) { render(); badge(); }
76
85
  });
77
86
  render();
78
87
  }
79
88
  export function handleMcpServersState(msg) {
80
89
  if (msg.slug && msg.slug !== store.get('currentSlug')) return;
81
- patch({ servers: msg.servers || [], loaded: true, extensionConnected: !!msg.extensionConnected, hostConnected: !!msg.hostConnected, extensionId: msg.extensionId || null });
90
+ patch({ servers: (msg.servers || []).map(function (row) { return row.source === 'computer' ? Object.assign({}, row, { id: 'client:' + row.id }) : row; }), xcode: msg.xcode || null, loaded: true, extensionConnected: !!msg.extensionConnected, hostConnected: !!msg.hostConnected, extensionId: msg.extensionId || null });
82
91
  }
83
92
  export function setExtensionConnected(value) { patch({ extensionConnected: !!value }); }
84
93
  export function getMcpServers() { return state().servers; }
85
94
  export function handleMcpConnectionMessage(msg) {
86
- if (msg.slug && msg.slug !== store.get('currentSlug')) return false;
95
+ if (msg.slug && msg.slug !== store.get('currentSlug') && msg.type !== 'mcp_settings_request') return false;
96
+ if (msg.type === 'mcp_settings_request') {
97
+ var accepted = false;
98
+ if (msg.slug === store.get('currentSlug') && msg.sessionId === store.get('activeSessionId') && ['client', 'credentials', 'token', 'permissions'].includes(msg.screen)) {
99
+ var row = state().servers.find(function (item) { return item.id === msg.connectionId; });
100
+ if (msg.screen === 'client' || row) {
101
+ navigate(msg.screen === 'client' ? 'client' : 'detail', row && row.id);
102
+ if (msg.screen === 'permissions') patch({ detailTab: 'permissions' });
103
+ openMcpSkillsWorkbench('mcp');
104
+ var root = document.getElementById('mcp-content');
105
+ var selector = msg.screen === 'credentials' ? '[data-form="credentials"]' : msg.screen === 'token' ? '[data-form="token"]' : null;
106
+ var form = root && selector && root.querySelector(selector);
107
+ accepted = !selector || !!form;
108
+ if (form) { var details = form.closest('details'); if (details) details.open = true; var input = form.querySelector('input'); if (input) input.focus({ preventScroll: true }); }
109
+ }
110
+ }
111
+ send({ type: 'mcp_settings_result', requestId: msg.requestId, slug: msg.slug, sessionId: msg.sessionId, accepted: accepted });
112
+ return true;
113
+ }
87
114
  if (msg.type === 'mcp_discovery_result') {
88
115
  var scanPending = state().pending;
89
116
  if (!scanPending || scanPending.requestId !== msg.requestId) return true;
@@ -96,9 +123,11 @@ export function handleMcpConnectionMessage(msg) {
96
123
  if (msg.requestId && (!pending || msg.requestId !== pending.requestId)) return true;
97
124
  clearActionTimer();
98
125
  patch({ pending: null, error: msg.ok ? '' : msg.error || 'Could not update connection.' });
99
- if (msg.ok && (msg.action === 'add' || msg.action === 'import')) { store.set({ mcpConnectionDraft: '' }); navigate('detail', msg.id); }
126
+ if (msg.ok && (!pending || pending.screen === state().screen) && (msg.action === 'add' || msg.action === 'add_local' || msg.action === 'import')) { store.set({ mcpConnectionDraft: '' }); if (msg.action === 'add_local') patch({ localDraft: null }); navigate('detail', msg.id); }
100
127
  if (msg.ok && msg.action === 'remove') navigate('list');
101
128
  if (msg.ok && msg.action === 'enable') patch({ notice: 'Saved. Tool availability updates on the next turn; some runtimes may need a new session.' });
129
+ if (msg.ok && msg.action === 'xcode_connect') patch({ notice: 'Xcode tools enabled. Use them on your next turn; some runtimes may need a new session.' });
130
+ if (msg.ok && msg.action === 'xcode_disconnect') patch({ notice: 'Xcode tools disabled. Work already performed in Xcode is not undone.' });
102
131
  return true;
103
132
  }
104
133
  if (msg.type === 'mcp_login_ready') {
@@ -0,0 +1,42 @@
1
+ import { escapeHtml } from './utils.js';
2
+ import { iconHtml, refreshIcons } from './icons.js';
3
+
4
+ function button(label, action, primary, disabled) {
5
+ return '<button type="button" class="mc-button' + (primary ? ' mc-primary' : '') + '" data-xcode="' + action + '"' + (disabled ? ' disabled' : '') + '>' + label + '</button>';
6
+ }
7
+ export function renderXcode(root, state, events) {
8
+ var focused = root.contains(document.activeElement) && document.activeElement.dataset.xcode;
9
+ var open = Array.from(root.querySelectorAll('details[open]')).map(function (item) { return item.dataset.tool; });
10
+ var row = (state.servers || []).find(function (item) { return item.integration === 'xcode'; });
11
+ var check = state.xcode, busy = !!state.pending;
12
+ var connected = !!(row && row.projectEnabled), ready = row && row.status === 'ready';
13
+ var status = connected ? ready ? 'Connected' : row.status === 'unavailable' ? 'Connection unavailable' : 'Enabled · connects when used' : 'Not connected';
14
+ var html = '<div class="mc-xcode"><div class="mc-heading"><span class="mc-emblem">' + iconHtml('hammer') + '</span><h2>Xcode</h2><p>Build and test your Apple apps from your Clay Studio conversations.</p></div>';
15
+ html += '<p class="mc-status" data-status="' + (connected && ready ? 'ready' : 'idle') + '"><span aria-hidden="true"></span>' + status + '</p>';
16
+ html += '<p class="mc-footnote">Xcode must run on the same Mac and under the same macOS user as the Clay Studio server.</p>';
17
+ var steps = '<ol class="mc-steps mc-xcode-steps"><li><span class="mc-step-marker">1</span><div><strong>Open your project in Xcode</strong><p>Keep Xcode open while your agent uses its tools.</p></div></li><li><span class="mc-step-marker">2</span><div><strong>Allow external agents</strong><p>In Xcode Settings → Intelligence, turn on “Allow external agents to use Xcode tools”. Approve Clay’s connection in Xcode if asked.</p></div></li><li><span class="mc-step-marker">3</span><div><strong>Connect to Clay Studio</strong><p>No commands, vendor configuration, or browser extension required.</p></div></li></ol>';
18
+ html += connected ? '<details class="mc-manage" data-tool="setup"' + (open.includes('setup') ? ' open' : '') + '><summary>Setup instructions</summary>' + steps + '</details>' : steps;
19
+ if (check && (!connected || !check.ready)) html += '<p class="mc-notice" role="status">' + escapeHtml(check.message) + '</p>';
20
+ if (state.error) html += '<p class="mc-alert" role="alert">' + escapeHtml(state.error) + '</p>';
21
+ if (row && row.error && row.error !== state.error) html += '<p class="mc-alert" role="status">' + escapeHtml(row.error) + '</p>';
22
+ if (state.notice) html += '<p class="mc-notice" role="status">' + escapeHtml(state.notice) + '</p>';
23
+ html += '<div class="mc-detail-actions">' + button(connected ? 'Reconnect Xcode' : 'Connect Xcode', 'connect', true, busy || !state.loaded || !!(check && !check.ready)) + button('Check again', 'check', false, busy) + (busy && state.pending.action === 'xcode_connect' ? button('Cancel connection', 'disconnect', false, false) : connected ? button('Disconnect', 'disconnect', false, false) : row ? button('Remove connection', 'remove', false, busy) : '') + '</div>';
24
+ if (busy) html += '<p class="mc-working" role="status">' + iconHtml('loader-circle') + (state.pending.action === 'xcode_check' ? 'Checking this Mac…' : 'Updating connection…') + '</p>';
25
+ if (row && row.tools && row.tools.length) {
26
+ html += '<div class="mc-section-heading"><h2>Available tools (' + row.tools.length + ')</h2></div><div class="mc-tools">';
27
+ html += row.tools.map(function (tool) { return '<details data-tool="' + escapeHtml(tool.name) + '"' + (open.includes(tool.name) ? ' open' : '') + '><summary>' + escapeHtml(tool.name) + '</summary><p>' + escapeHtml(tool.description || 'No description provided.') + '</p></details>'; }).join('') + '</div>';
28
+ }
29
+ html += '<p class="mc-footnote">Connect enables these tools for your supported private sessions and Mates. Tools become available on the next turn; some runtimes need a new session. Your session’s tool approval policy still applies. Disconnect blocks further calls but cannot undo work already performed in Xcode.</p></div>';
30
+ root.innerHTML = html;
31
+ root.querySelectorAll('[data-xcode]').forEach(function (element) {
32
+ element.onclick = function () {
33
+ var action = element.dataset.xcode;
34
+ if (action === 'connect') events.action('xcode_connect');
35
+ if (action === 'check') events.action('xcode_check');
36
+ if (action === 'disconnect') events.disconnect();
37
+ if (action === 'remove' && row) events.action('remove', { id: row.id });
38
+ };
39
+ });
40
+ if (focused) { var target = root.querySelector('[data-xcode="' + focused + '"]'); if (target && !target.disabled) target.focus({ preventScroll: true }); }
41
+ refreshIcons(root);
42
+ }
@@ -1,3 +1,4 @@
1
+ import { mountOwnershipRecovery } from './project-ownership-recovery.js';
1
2
  // Restricted projects use public shell primitives without opening a project socket.
2
3
  import { createStore, store } from './store.js';
3
4
  import { groupProjects, getProjectAbbrev } from './project-grouping.js';
@@ -134,3 +135,17 @@ document.addEventListener('visibilitychange', function () { if (document.hidden)
134
135
  window.addEventListener('pagehide', function () { clearTimeout(store.get('adminUsageTimer')); store.set({ adminUsageGeneration: store.get('adminUsageGeneration') + 1 }); });
135
136
  window.addEventListener('pageshow', function (event) { if (event.persisted) { clearUsage(); store.set({ adminUsageLoading: false }); loadUsage(false); } });
136
137
  loadUsage(false);
138
+
139
+ if (data.project.ownershipRecovery) {
140
+ var recovery = document.createElement('div'); recovery.id = 'overview-ownership-recovery'; recovery.className = 'ownership-recovery';
141
+ document.getElementById('access-panel').appendChild(recovery);
142
+ if (data.project.isWorktree) {
143
+ var parentLink = document.createElement('a'); parentLink.href = '/p/' + encodeURIComponent(data.project.parentSlug) + '/'; parentLink.textContent = 'Recover ownership in the parent project'; recovery.appendChild(parentLink);
144
+ } else mountOwnershipRecovery(recovery, data.project.slug);
145
+ }
146
+
147
+ if (data.project.ownershipRecovery) {
148
+ var recoverLink = document.createElement('button'); recoverLink.type = 'button'; recoverLink.className = 'settings-btn-sm'; recoverLink.textContent = 'Recover ownership';
149
+ recoverLink.onclick = function () { document.getElementById('access-tab').click(); document.getElementById('access-tab').focus(); };
150
+ document.querySelector('.project-admin-notice').appendChild(recoverLink);
151
+ }
@@ -0,0 +1,75 @@
1
+ import { store } from './store.js';
2
+
3
+ function node(tag, text, className) { var el = document.createElement(tag); if (text) el.textContent = text; if (className) el.className = className; return el; }
4
+ function action(text, fn) { var el = node('button', text, 'settings-btn-sm'); el.type = 'button'; el.onclick = fn; return el; }
5
+ async function request(slug, data) {
6
+ var response = await fetch('/api/project-settings/' + encodeURIComponent(slug) + '/ownership', {
7
+ method: data ? 'POST' : 'GET', credentials: 'same-origin', signal: AbortSignal.timeout(10000),
8
+ headers: { 'Content-Type': 'application/json' }, body: data ? JSON.stringify(data) : undefined
9
+ });
10
+ var result = await response.json(); if (!response.ok) throw new Error(result.error || 'Recovery check failed.'); return result;
11
+ }
12
+ export function mountOwnershipRecovery(root, slug) {
13
+ var key = root.id, token = crypto.randomUUID();
14
+ var panels = Object.assign({}, store.get('ownershipRecoveryPanels'));
15
+ panels[key] = { slug: slug, token: token }; store.set({ ownershipRecoveryPanels: panels });
16
+ function current() { var item = (store.get('ownershipRecoveryPanels') || {})[key]; return root.isConnected && item && item.token === token; }
17
+ function status(text) { var el = node('p', text, 'settings-status'); el.setAttribute('role', 'status'); return el; }
18
+ async function check() {
19
+ if (!current()) return;
20
+ root.replaceChildren(status('Checking ownership…'));
21
+ try { var result = await request(slug); if (current()) render(result); }
22
+ catch (error) { if (current()) root.replaceChildren(status(error.message), action('Check again', check)); }
23
+ }
24
+ function render(result, approvalCode) {
25
+ root.replaceChildren(node('h3', result.status === 'healthy' ? 'Ownership verified' : 'Ownership recovery'), status(result.message));
26
+ root.appendChild(node('p', 'Checked ' + new Date(result.checkedAt).toLocaleTimeString() + '. Recovery keeps session owners and sharing unchanged.', 'settings-hint'));
27
+ if (result.owner) root.appendChild(node('p', (result.status === 'ready' ? 'Proposed recovery owner: ' : 'Owner: ') + result.owner.name));
28
+ if (result.expiresAt) root.appendChild(node('p', 'Server approval expires ' + new Date(result.expiresAt).toLocaleTimeString() + '.', 'settings-hint'));
29
+ var controls = node('div', '', 'settings-form-actions'); controls.appendChild(action('Check again', check));
30
+ if (result.status === 'ready') controls.appendChild(action('Review recovery', function () {
31
+ if (!current()) return;
32
+ var review = node('div', '', 'ownership-review');
33
+ review.appendChild(node('p', 'Restore ' + slug + ' to ' + result.owner.name + '? This updates the parent and all its worktrees. Private session ownership stays unchanged.'));
34
+ review.append(action('Cancel', function () { render(result, approvalCode); }), action('Recover ownership', async function () {
35
+ if (!current()) return;
36
+ root.replaceChildren(status('Recovering ownership…'));
37
+ try {
38
+ var saved = await request(slug, approvalCode ? { revision: result.revision, approvalCode: approvalCode } : { revision: result.revision });
39
+ if (current()) root.replaceChildren(status('Ownership recovered for ' + saved.owner.name + '.'), action('Reload project', function () { location.assign('/p/' + encodeURIComponent(slug) + '/'); }));
40
+ } catch (error) {
41
+ if (current()) root.replaceChildren(status(error.message + ' The result may be unknown if the connection was interrupted. Check the saved ownership before another review.'), action('Check again', check));
42
+ }
43
+ }));
44
+ root.appendChild(review); review.querySelector('button').focus();
45
+ }));
46
+ root.appendChild(controls);
47
+ if (result.operatorApprovalAvailable && result.status === 'blocked') {
48
+ var approval = node('details'); approval.open = true; approval.appendChild(node('summary', 'Server approval'));
49
+ approval.appendChild(node('p', 'Ask the operator of the machine running Clay Studio to approve this project and an existing account. This works without a system-user mapping. Administrator status in the browser alone cannot approve recovery.'));
50
+ var command = node('code', 'npx clay-server --authorize-project-recovery ' + slug + ' --owner <existing-username>');
51
+ approval.appendChild(command);
52
+ approval.appendChild(node('p', 'For a development daemon, use node bin/cli.js --dev in place of npx clay-server. Run the command with the same OS account and CLAY_HOME as the running server. The code expires after 10 minutes or a daemon restart.'));
53
+ var form = node('form'), label = node('label', 'Approval code'), input = node('input');
54
+ input.type = 'password'; input.autocomplete = 'off'; input.spellcheck = false; input.required = true; input.maxLength = 48;
55
+ input.setAttribute('aria-label', 'Approval code'); input.className = 'settings-input'; label.appendChild(input);
56
+ var verify = node('button', 'Review server approval', 'settings-btn-sm'); verify.type = 'submit';
57
+ var feedback = status(''); form.append(label, verify, feedback); approval.appendChild(form); root.appendChild(approval);
58
+ form.onsubmit = async function (event) {
59
+ event.preventDefault(); if (!current()) return; verify.disabled = true;
60
+ var code = input.value.trim();
61
+ try { var reviewed = await request(slug, { approvalCode: code }); if (current()) { input.value = ''; render(reviewed, code); } }
62
+ catch (error) { if (current()) { feedback.textContent = error.message; verify.disabled = false; } }
63
+ };
64
+ }
65
+ if (result.status !== 'healthy') {
66
+ var help = node('details'); help.appendChild(node('summary', result.operatorApprovalAvailable ? 'Directory and account diagnostics' : 'Server operator instructions'));
67
+ help.appendChild(node('p', 'On the system running Clay Studio, verify the original project directory, its filesystem owner, and the original account’s provisioned system user and home. Restore missing accounts or mounts through your normal server provisioning process. Resolve shared UIDs, overlapping homes or symlink aliases before checking again.'));
68
+ help.appendChild(node('p', 'Application administrator status cannot prove private project ownership. Do not assign an arbitrary account or change filesystem ownership just to pass this check.'));
69
+ help.appendChild(action('Copy diagnostic summary', function () {
70
+ navigator.clipboard.writeText(JSON.stringify({ project: slug, status: result.status, code: result.code, message: result.message }, null, 2)).then(function () { if (current()) help.appendChild(status('Diagnostic summary copied.')); }, function () { if (current()) help.appendChild(status('Copy unavailable. Select the diagnostic text above.')); });
71
+ })); root.appendChild(help);
72
+ }
73
+ }
74
+ check();
75
+ }
@@ -56,7 +56,7 @@ function visibilityAccess(project) {
56
56
  var permitted = !store.get('permissions') || store.get('permissions').projectSettings !== false;
57
57
  var owner = !!(project && project.projectOwnerId && project.projectOwnerId === userId);
58
58
  var admin = !!(currentUser && currentUser.role === "admin");
59
- var multi = !!(store.get('isMultiUserMode') && project && permitted);
59
+ var multi = !!(store.get('isMultiUserMode') && project && project.contentAccess !== false && permitted);
60
60
  return { visible: multi && (owner || admin), editable: multi && owner };
61
61
  }
62
62
 
@@ -0,0 +1,91 @@
1
+ import { enhanceSettingsSelects } from './settings-select.js';
2
+ import { store } from './store.js';
3
+ import { openSettings } from './settings-shell.js';
4
+ import { mountOwnershipRecovery } from './project-ownership-recovery.js';
5
+ import { confirmSettingsAction } from './server-settings-state.js';
6
+
7
+ function node(tag, text, className) { var el = document.createElement(tag); el.textContent = text || ''; if (className) el.className = className; return el; }
8
+ function button(text, fn) { var el = node('button', text, 'settings-btn-sm'); el.type = 'button'; el.onclick = fn; return el; }
9
+ async function request(slug, suffix, data) {
10
+ var response = await fetch('/api/admin/projects/' + encodeURIComponent(slug) + '/' + suffix, { credentials: 'same-origin', method: data ? 'PUT' : 'GET', headers: { 'Content-Type': 'application/json' }, body: data ? JSON.stringify(data) : undefined, signal: AbortSignal.timeout(10000) });
11
+ var result = await response.json(); if (!response.ok) { var error = new Error(result.error || 'Project access unavailable.'); error.status = response.status; throw error; } return result;
12
+ }
13
+ export function clearProjectSettingsAccess() { store.set({ projectSettingsAccess: null }); }
14
+ export function loadProjectSettingsAccess(slug, project) {
15
+ var root = document.getElementById('ps-access-management');
16
+ var token = crypto.randomUUID(); store.set({ projectSettingsAccess: { slug: slug, token: token } });
17
+ function current() { var s = store.get('projectSettingsAccess'); return s && s.token === token && store.get('projectSettingsSlug') === slug; }
18
+ function update(values) { if (current()) store.set({ projectSettingsAccess: Object.assign({}, store.get('projectSettingsAccess'), values) }); }
19
+ function reload() { if (current()) loadProjectSettingsAccess(slug, project); }
20
+ root.replaceChildren();
21
+ if (!store.get('isMultiUserMode')) { root.appendChild(node('p', 'This single-user server is private to its operator.', 'settings-hint')); return; }
22
+ root.appendChild(node('p', 'Loading access…', 'settings-status'));
23
+ request(slug, 'access').then(function (access) {
24
+ if (!current()) return;
25
+ root.replaceChildren();
26
+ var ownerId = access.ownerId || access.projectOwnerId;
27
+ var owner = ownerId === store.get('myUserId');
28
+ var inherited = project.isWorktree;
29
+ var parentSlug = project.parentSlug || access.parentSlug;
30
+ var ownerAccount = (store.get('cachedAllUsers') || []).find(function (account) { return account.id === ownerId; });
31
+ root.appendChild(node('p', 'Owner: ' + (access.ownerName || ownerAccount && (ownerAccount.displayName || ownerAccount.username) || ownerId || 'Ownership needs recovery')));
32
+ root.appendChild(node('p', 'Project access: ' + (access.visibility === 'public' ? 'Public — authenticated users' : 'Private')));
33
+ if (inherited) {
34
+ root.appendChild(node('p', 'Inherited from ' + parentSlug + '. Parent access covers every existing and future worktree.', 'settings-hint'));
35
+ root.appendChild(button('Manage parent access', function () { openSettings({ scope: 'project', slug: parentSlug, page: 'access' }); }));
36
+ } else root.appendChild(node('p', 'Access applies to this project and all existing and future worktrees. Removing a parent grant removes inherited access; separate exact-worktree grants remain independent.', 'settings-hint'));
37
+ if (owner && !inherited) root.appendChild(button('Manage access and ownership', function () { edit(access); }));
38
+ if (!owner) root.appendChild(node('p', 'Only the verified owner can change project access. Project content remains subject to your current permissions.', 'settings-hint'));
39
+ if (project.ownershipRecovery || access.ownershipRecovery || !ownerId) {
40
+ var recovery = node('div', '', 'ownership-recovery'); recovery.id = 'ps-ownership-recovery'; root.appendChild(recovery);
41
+ if (inherited) recovery.appendChild(node('p', 'Recover ownership in the parent project.', 'settings-hint'));
42
+ else mountOwnershipRecovery(recovery, slug);
43
+ }
44
+ root.appendChild(button('Refresh access', reload));
45
+ }).catch(function (error) {
46
+ if (!current()) return;
47
+ root.replaceChildren(node('p', error.status === 403 ? 'Only the project owner can inspect or change detailed access settings.' : error.message, 'settings-status'));
48
+ if (error.status === 403 && project.contentAccess !== false && project.isWorktree) {
49
+ root.appendChild(node('p', 'Inherited from ' + project.parentSlug + '. Parent access covers every existing and future worktree.', 'settings-hint'));
50
+ if ((store.get('projectsHubList') || []).some(function (entry) { return entry.slug === project.parentSlug; })) root.appendChild(button('Manage parent access', function () { openSettings({ scope: 'project', slug: project.parentSlug, page: 'access' }); }));
51
+ }
52
+ root.appendChild(button('Retry', reload));
53
+ });
54
+ async function edit(access) {
55
+ var response;
56
+ try { response = await fetch('/api/admin/users', { credentials: 'same-origin', signal: AbortSignal.timeout(10000) }); var data = await response.json(); if (!response.ok) throw new Error(data.error || 'Accounts unavailable.'); }
57
+ catch (error) { if (current()) root.appendChild(node('p', error.message, 'settings-status')); return; }
58
+ if (!current()) return;
59
+ var users = data.users || [];
60
+ var editor = node('div', '', 'ps-access-editor'); root.replaceChildren(editor);
61
+ editor.addEventListener('change', function () { update({ dirty: true }); });
62
+ var status = node('p', '', 'settings-status'); status.setAttribute('role', 'status');
63
+ async function save(suffix, value) {
64
+ if (!current()) return;
65
+ update({ saving: true });
66
+ Array.from(editor.querySelectorAll('button,input,select')).forEach(function (el) { el.disabled = true; if (el.tagName === 'SELECT') el.dispatchEvent(new Event('settings-sync')); }); status.textContent = 'Saving…';
67
+ try { await request(slug, suffix, value); if (current()) { status.textContent = 'Saved.'; reload(); } }
68
+ catch (error) { if (current()) { update({ saving: false }); status.textContent = error.message + ' Check the saved state before retrying; your draft is retained.'; Array.from(editor.querySelectorAll('button,input,select')).forEach(function (el) { el.disabled = false; if (el.tagName === 'SELECT') el.dispatchEvent(new Event('settings-sync')); }); } }
69
+ }
70
+ var visibility = node('select'); visibility.setAttribute('aria-label', 'Project access');
71
+ ['private', 'public'].forEach(function (value) { var option = node('option', value === 'private' ? 'Private' : 'Public — authenticated users'); option.value = value; visibility.appendChild(option); }); visibility.value = access.visibility;
72
+ editor.append(node('h3', 'Project access'), visibility, button('Save project access', function () { var value = visibility.value; confirmSettingsAction('Change access for this project and all its worktrees to ' + value + '?', 'Save project access', function () { save('visibility', { visibility: value }); }); }));
73
+ var members = node('div');
74
+ users.filter(function (user) { return user.id !== access.ownerId; }).forEach(function (user) {
75
+ var label = node('label', '', 'ps-access-member'); var input = node('input'); input.type = 'checkbox'; input.value = user.id; input.checked = (access.allowedUsers || []).includes(user.id);
76
+ label.append(input, node('span', user.displayName || user.username)); members.appendChild(label);
77
+ });
78
+ editor.append(node('h3', 'Allowed users'), node('p', 'These grants cover all worktrees. Public access takes precedence while the project is public.', 'settings-hint'), members,
79
+ button('Save allowed users', function () { save('users', { allowedUsers: Array.from(members.querySelectorAll('input:checked')).map(function (el) { return el.value; }) }); }));
80
+ var owners = node('select'); owners.setAttribute('aria-label', 'New project owner');
81
+ users.forEach(function (user) { var option = node('option', user.displayName || user.username); option.value = user.id; owners.appendChild(option); }); owners.value = access.ownerId;
82
+ editor.append(node('h3', 'Transfer ownership'), owners, button('Review ownership transfer', function () {
83
+ if (owners.value === access.ownerId) { status.textContent = 'Choose a different owner.'; return; }
84
+ var nextOwner = owners.value;
85
+ confirmSettingsAction('Transfer this project and its worktrees to ' + owners.selectedOptions[0].textContent + '? Existing session owners stay unchanged. You may lose access.', 'Transfer ownership', function () { save('owner', { userId: nextOwner }); });
86
+ }), status, button('Back to access', function () {
87
+ if ((store.get('projectSettingsAccess') || {}).dirty) confirmSettingsAction('Discard unsaved access changes?', 'Discard changes', reload); else reload();
88
+ }));
89
+ enhanceSettingsSelects(editor);
90
+ }
91
+ }
@@ -5,7 +5,7 @@ import { parseEnvString, serializeEnvValue, looksLikeEnv } from './settings-env-
5
5
 
6
6
  function state() { return store.get('projectEnvironmentEditor') || {}; }
7
7
  function update(values) { store.set({ projectEnvironmentEditor: Object.assign({}, state(), values) }); }
8
- function status(text) { document.getElementById('ps-env-save-status').textContent = text; }
8
+ function status(text) { document.getElementById('ps-env-save-status').textContent = text; var retry = document.getElementById('ps-env-retry'); if (retry) retry.hidden = !state().slug || !!state().loaded || !!state().loading; }
9
9
  function send(message) {
10
10
  var ws = getWs();
11
11
  if (!ws || ws.readyState !== 1) { status('Disconnected. Your draft is kept. Reconnect and try again.'); return false; }
@@ -22,7 +22,7 @@ export function openProjectEnvironment(slug) {
22
22
  render(); status('Loading…');
23
23
  var requestId = crypto.randomUUID();
24
24
  update({ requestId: requestId });
25
- if (send({ type: 'get_project_env', slug: slug, requestId: requestId })) update({ loading: true });
25
+ if (send({ type: 'get_project_env', slug: slug, requestId: requestId })) { update({ loading: true }); status('Loading…'); }
26
26
  }
27
27
  export function handleProjectEnv(msg) {
28
28
  if (!state().loading || (msg.slug !== state().slug || msg.requestId !== state().requestId)) return;
@@ -104,6 +104,7 @@ function save() {
104
104
  update({ submitted: envrc, saving: true }); render(); status('Saving…');
105
105
  }
106
106
  export function initProjectEnvironment() {
107
+ var retry = document.getElementById('ps-env-retry'); if (retry) retry.onclick = function () { openProjectEnvironment(store.get('projectSettingsSlug')); };
107
108
  document.getElementById('ps-env-add-btn').onclick = function () { changeRows((state().rows || []).concat([{ key: '', value: '' }])); render(); document.querySelector('#ps-env-list .ps-env-row:last-child input').focus(); };
108
109
  document.getElementById('ps-env-save').onclick = save;
109
110
  store.subscribe(function (next, previous) {
@@ -1,3 +1,4 @@
1
+ import { loadProjectSettingsAccess, clearProjectSettingsAccess } from './project-settings-access.js';
1
2
  import { store } from './store.js';
2
3
  import { getWs } from './ws-ref.js';
3
4
  import { initProjectEnvironment, openProjectEnvironment, projectEnvironmentDirty, discardProjectEnvironment } from './project-settings-environment.js';
@@ -34,10 +35,15 @@ var controller = {
34
35
  enter: function () {},
35
36
  activate: function (page) { switchSection(page); },
36
37
  leave: function () { closePsEmojiPicker(); },
37
- busy: function (kind) { return kind !== "page" && (store.get("projectEnvironmentEditor") || {}).saving ? "Wait for the environment save to finish." : ""; },
38
+ busy: function (kind) { if ((store.get("projectSettingsAccess") || {}).saving) return "Wait for the access save to finish."; return kind !== "page" && (store.get("projectEnvironmentEditor") || {}).saving ? "Wait for the environment save to finish." : ""; },
38
39
  leavePrompt: function (kind) {
40
+ var access = store.get("projectSettingsAccess");
39
41
  var env = projectEnvironmentDirty();
40
42
  var rename = renameDirty();
43
+ if (kind !== "page" && access && access.dirty) return {
44
+ message: kind === "close" ? "Discard unsaved project changes and close?" : "Discard unsaved project access and name changes? Environment drafts remain in this tab.",
45
+ action: "Discard changes", apply: function () { clearProjectSettingsAccess(); if (kind === "close") discardDrafts(); else cancelRename(); }
46
+ };
41
47
  if (!env && !rename) return null;
42
48
  if (kind === "close") return { message: "Your changes have not been saved. Discard them and close?", action: "Discard changes", apply: discardDrafts };
43
49
  if (kind === "page") return null;
@@ -122,18 +128,26 @@ function bindProjectSettings(slug, project) {
122
128
  if (env && !env.dirty && !env.saving) store.set({ projectEnvironmentEditor: Object.assign({}, env, { loaded: false, loading: false }) });
123
129
  if (same) refreshProjectSettings(slug, project);
124
130
  else { closePsEmojiPicker(); populateProfile(); }
125
- var active = panelEl.querySelector(".ps-section.active");
126
- if (active && active.dataset.section === "environment") openProjectEnvironment(slug);
131
+ loadProjectSettingsAccess(slug, project);
132
+ if (project.contentAccess !== false) openProjectEnvironment(slug);
127
133
  }
128
134
 
129
135
  function refreshProjectSettings(slug, project) {
130
136
  if (settingsSlug() !== slug) return;
137
+ var previousProject = settingsProject();
138
+ var changedAccess = previousProject && (previousProject.contentAccess !== project.contentAccess || previousProject.projectOwnerId !== project.projectOwnerId || previousProject.ownershipRecovery !== project.ownershipRecovery);
139
+ if (project.contentAccess === false) {
140
+ store.set({ projectEnvironmentEditor: {}, projectEnvironmentDrafts: {} });
141
+ document.getElementById('ps-env-list').replaceChildren();
142
+ }
131
143
  var name = project.title || project.project || project.name || slug;
132
144
  store.set({ projectSettingsProject: Object.assign({}, project, { name: name }) });
133
145
  var nameEl = document.getElementById("ps-project-name");
134
146
  if (nameEl) nameEl.textContent = name || "-";
135
147
  updateIconPreview(project.icon || null);
148
+ if (changedAccess) { loadProjectSettingsAccess(slug, project); switchSection(); }
136
149
  populateProjectSessionVisibilitySettings(slug, settingsProject());
150
+ document.getElementById("ps-target-title").textContent = name;
137
151
  document.getElementById('ps-project-path').textContent = project.path || (slug === store.get('currentSlug') ? store.get('cwd') : '') || 'Folder information unavailable';
138
152
  }
139
153
 
@@ -144,6 +158,12 @@ function clearProjectSettings(slug) {
144
158
  delete drafts[slug];
145
159
  store.set({ projectSettingsSlug: null, projectSettingsProject: null, projectEnvironmentDrafts: drafts });
146
160
  if (env.slug === slug) { store.set({ projectEnvironmentEditor: {} }); }
161
+ clearProjectSettingsAccess();
162
+ document.getElementById('ps-access-management').replaceChildren();
163
+ document.getElementById('ps-target-title').textContent = '';
164
+ document.getElementById('ps-target-context').textContent = '';
165
+ var openLink = document.getElementById('ps-open-project'); if (openLink) openLink.hidden = true;
166
+ document.getElementById('ps-env-list').replaceChildren();
147
167
  closePsEmojiPicker();
148
168
  cancelRename();
149
169
  }
@@ -192,12 +212,26 @@ export function isProjectSettingsOpen() {
192
212
  }
193
213
 
194
214
  function switchSection(name) {
215
+ var project = settingsProject();
216
+ var restricted = project && project.contentAccess === false;
217
+ var editable = !store.get('isMultiUserMode') || project && project.projectOwnerId === store.get('myUserId');
218
+ ['ps-rename-btn', 'ps-icon-btn', 'ps-icon-remove-btn'].forEach(function (id) { document.getElementById(id).disabled = !editable || restricted; });
195
219
  for (var j = 0; j < sections.length; j++) {
196
- sections[j].classList.toggle("active", sections[j].dataset.section === name);
220
+ sections[j].classList.add("active");
221
+ sections[j].hidden = !!restricted && sections[j].dataset.section !== "access";
197
222
  }
198
- if (name === "environment" && settingsSlug()) openProjectEnvironment(settingsSlug());
223
+ var title = document.getElementById('ps-target-title');
224
+ title.textContent = project ? project.name : '';
225
+ var openLink = document.getElementById('ps-open-project'); if (openLink) openLink.hidden = !project;
226
+ if (project && openLink) { openLink.href = '/p/' + encodeURIComponent(settingsSlug()) + '/'; openLink.textContent = restricted ? 'Open overview' : 'Open project'; }
227
+ document.getElementById('ps-target-context').textContent = !project ? '' : restricted ? 'Administrative metadata only' : project.isWorktree ? 'Worktree / ' + (project.parentSlug || '') : 'Project settings';
228
+ if (project && !restricted) openProjectEnvironment(settingsSlug());
199
229
  enhanceSettingsSelects(panelEl);
200
230
  refreshIcons();
231
+ if (name && name !== 'profile') requestAnimationFrame(function () {
232
+ var section = panelEl.querySelector('[data-section="' + name + '"]');
233
+ if (section && !section.hidden) section.scrollIntoView({ block: 'start' });
234
+ });
201
235
  }
202
236
 
203
237
  function populateProfile() {
@@ -41,7 +41,7 @@ function focusHeading() {
41
41
  // last project, then the current one, then the first ordinary project. Only
42
42
  // projects present in the server-provided list qualify.
43
43
  function workspaceFallback() {
44
- var known = ordinaryProjects(store.get('projectsHubList')).map(function (project) { return project.slug; });
44
+ var known = ordinaryProjects(store.get('projectsHubList')).filter(function (project) { return project.contentAccess !== false; }).map(function (project) { return project.slug; });
45
45
  var choices = [store.get('homeSurfaceProjectSlug'), store.get('currentSlug'), known[0]];
46
46
  for (var i = 0; i < choices.length; i++) if (choices[i] && known.indexOf(choices[i]) !== -1) return choices[i];
47
47
  return null;
@@ -49,7 +49,7 @@ function workspaceFallback() {
49
49
 
50
50
  // Shows the loading or zero-project welcome; with projects present it opens a workspace instead.
51
51
  export function showProjectsHub(fromHistory) {
52
- if (store.get('projectListLoaded') && ordinaryProjects(store.get('projectsHubList')).length) {
52
+ if (store.get('projectListLoaded') && workspaceFallback()) {
53
53
  var slug = workspaceFallback();
54
54
  if (slug) {
55
55
  hideProjectsHub();
@@ -103,7 +103,7 @@ export function initProjectsHub() {
103
103
  }
104
104
  if (!state.projectsHubVisible) return;
105
105
  // A project already being opened keeps its own activation; otherwise known projects replace the hub.
106
- if (state.projectListLoaded && !state.pendingHomeProjectSlug && ordinaryProjects(state.projectsHubList).length) { showProjectsHub(true); return; }
106
+ if (state.projectListLoaded && !state.pendingHomeProjectSlug && workspaceFallback()) { showProjectsHub(true); return; }
107
107
  if (state.projectsHubList !== previous.projectsHubList || state.projectListLoaded !== previous.projectListLoaded ||
108
108
  state.homeSurfaceLoaded !== previous.homeSurfaceLoaded || state.onboardingStep !== previous.onboardingStep ||
109
109
  state.projectsAccessLoaded !== previous.projectsAccessLoaded || state.permissions !== previous.permissions ||
@@ -0,0 +1,74 @@
1
+ import { store } from './store.js';
2
+ import { groupProjects } from './project-grouping.js';
3
+
4
+ function state() { return store.get('settingsProjectTree') || { expanded: {}, query: '' }; }
5
+ function button(text, label, action) {
6
+ var node = document.createElement('button'); node.type = 'button'; node.textContent = text;
7
+ node.setAttribute('aria-label', label); node.onclick = action; return node;
8
+ }
9
+ export function renderProjectTree(choices, selected, onSelect, placeholder) {
10
+ var root = document.getElementById('settings-project-tree');
11
+ if (!root) return;
12
+ var focus = root.contains(document.activeElement) && document.activeElement.dataset.treeKey;
13
+ var data = state();
14
+ root.replaceChildren();
15
+ var search = document.createElement('input'); search.type = 'search'; search.placeholder = 'Find a project or worktree…';
16
+ search.setAttribute('aria-label', 'Find a project or worktree'); search.value = data.query; search.dataset.treeKey = 'search';
17
+ search.oninput = function () {
18
+ store.set({ settingsProjectTree: Object.assign({}, state(), { query: search.value }) });
19
+ renderProjectTree(choices, selected, onSelect, placeholder);
20
+ };
21
+ root.onkeydown = function (event) {
22
+ if (event.target === search) return;
23
+ var items = Array.from(root.querySelectorAll('button')).filter(function (el) { return !el.closest('[hidden]'); });
24
+ var index = items.indexOf(document.activeElement);
25
+ if (index < 0) return;
26
+ if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
27
+ event.preventDefault();
28
+ var next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : Math.max(0, Math.min(items.length - 1, index + (event.key === 'ArrowDown' ? 1 : -1)));
29
+ items[next].focus();
30
+ } else if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
31
+ var toggle = event.target.closest('.settings-project-row').querySelector('[aria-expanded]');
32
+ if (toggle && toggle.getAttribute('aria-expanded') !== String(event.key === 'ArrowRight')) { event.preventDefault(); toggle.click(); }
33
+ }
34
+ };
35
+ root.appendChild(search);
36
+ var list = document.createElement('div'); list.className = 'settings-project-list'; list.setAttribute('aria-label', 'Projects'); root.appendChild(list);
37
+ var query = data.query.trim().toLowerCase();
38
+ var grouped = groupProjects(choices.map(function (choice) { return Object.assign({}, choice.project, { settingsChoice: choice }); }));
39
+ function matches(project) { return !query || (project.settingsChoice.label + ' ' + project.slug).toLowerCase().includes(query); }
40
+ function row(project, children, child) {
41
+ var item = document.createElement('div'); item.className = 'settings-project-row' + (child ? ' settings-worktree-row' : '');
42
+ var expanded = !!data.expanded[project.slug];
43
+ if (children.length) {
44
+ var toggle = button(expanded ? '⌄' : '›', (expanded ? 'Collapse ' : 'Expand ') + project.settingsChoice.label + ' worktrees', function () {
45
+ var next = Object.assign({}, state().expanded); next[project.slug] = !expanded;
46
+ store.set({ settingsProjectTree: Object.assign({}, state(), { expanded: next }) });
47
+ renderProjectTree(choices, selected, onSelect, placeholder);
48
+ });
49
+ toggle.className = 'settings-project-expand'; toggle.dataset.treeKey = 'expand:' + project.slug;
50
+ toggle.setAttribute('aria-expanded', String(expanded)); toggle.setAttribute('aria-controls', 'settings-children-' + project.slug); item.appendChild(toggle);
51
+ } else { var spacer = document.createElement('span'); spacer.className = 'settings-project-expand-spacer'; item.appendChild(spacer); }
52
+ var select = button(project.settingsChoice.label, project.settingsChoice.label + (child ? ' worktree' : ' project'), function () { onSelect(project.slug); });
53
+ select.className = 'settings-project-item'; select.dataset.slug = project.slug; select.dataset.treeKey = 'select:' + project.slug;
54
+ select.classList.toggle('active', project.slug === selected);
55
+ if (project.slug === selected) select.setAttribute('aria-current', 'page');
56
+ var label = document.createElement('span'); label.className = 'settings-project-label'; label.textContent = project.settingsChoice.label;
57
+ var detail = document.createElement('small');
58
+ detail.textContent = project.ownershipRecovery ? 'Needs recovery' : children.length ? children.length + ' worktrees' : child ? 'Worktree' : '';
59
+ select.replaceChildren(label, detail); item.appendChild(select); list.appendChild(item);
60
+ if (children.length) {
61
+ var group = document.createElement('div'); group.id = 'settings-children-' + project.slug; group.hidden = !expanded; group.className = 'settings-project-children';
62
+ list.appendChild(group);
63
+ children.filter(function (entry) { return matches(project) || matches(entry); }).forEach(function (entry) {
64
+ row(entry, [], true); group.appendChild(list.lastChild);
65
+ });
66
+ }
67
+ }
68
+ grouped.parents.forEach(function (project) {
69
+ var children = grouped.wtByParent[project.slug] || [];
70
+ if (matches(project) || children.some(matches)) row(project, children, project.isWorktree);
71
+ });
72
+ if (!list.children.length) { var empty = document.createElement('p'); empty.className = 'settings-hint'; empty.textContent = choices.length ? 'No matching projects or worktrees.' : placeholder || 'No projects available'; list.appendChild(empty); }
73
+ if (focus) Array.from(root.querySelectorAll('[data-tree-key]')).some(function (node) { if (node.dataset.treeKey !== focus) return false; node.focus(); return true; });
74
+ }