pisha-server 0.0.0-stage → 0.0.11

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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1079 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +79 -0
  14. package/dashboard/dashboard.js +407 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +166 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2093 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +113 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
@@ -0,0 +1,151 @@
1
+ import { $ } from './dom.js'
2
+ import { T } from './i18n.js'
3
+ import { hosts, hostListeners, can } from './state.js'
4
+ import { esc, hhmm, now } from './format.js'
5
+ import { postJson, folderChips, addFolderDialog } from './machines.js'
6
+ import { agentMark } from './content.js'
7
+ import { newSessionDialog } from './squads.js'
8
+ import { currentRoute } from './router.js'
9
+
10
+ // A new machine, in one page: its name, the command to run on it, waiting for
11
+ // it to connect, and what to do once it has. The whole way is in sight from
12
+ // the start (what is not yet due, dimmed), and the page follows by itself.
13
+ // It survives going elsewhere and coming back: the code it made is kept.
14
+
15
+ let draft = null // { name, plugin, enroll, os, home, root, osUser, joined, error, generating, slowTimer, slow }
16
+ const fresh = () => ({ name: '', plugin: false, agents: ['claude'], enroll: null, os: /Mac/i.test(navigator.platform) ? 'macos' : /Win/i.test(navigator.platform) ? 'windows' : 'linux', home: false, root: false, osUser: '', joined: null, error: '', generating: false, slow: false })
17
+
18
+ const expired = () => draft.enroll && !draft.joined && draft.enroll.expires_at < now()
19
+ const cmdRow = text => `<div class="cmdrow"><pre class="cmd">${esc(text)}</pre><button type="button" class="btn" data-copy>${esc(T.copy)}</button></div>`
20
+ const step = (n, done, label) => `<li class="nt-step${done ? ' done' : ''}"><b aria-hidden="true">${done ? '✓' : n}</b>${esc(label)}${done ? `<span class="sr-only"> · ${esc(T.fsDone)}</span>` : ''}</li>`
21
+
22
+ function installHtml() {
23
+ const r = draft.enroll
24
+ const os = draft.os
25
+ const insecure = /^http:\/\//.test(r.server_url) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(r.server_url)
26
+ // The agents to install: Claude Code unless left out, Codex and Grok when chosen.
27
+ const agents = (draft.agents.includes('claude') ? '' : ' --no-claude') + (draft.agents.includes('codex') ? ' --codex' : '') + (draft.agents.includes('grok') ? ' --grok' : '')
28
+ const extra = agents + (draft.home ? ' --allow-home' : '') + (draft.root && os !== 'macos' ? ' --allow-root' : '') + (insecure ? ' --insecure' : '')
29
+ // (A new system user needs root: the installer does the rest as that user.)
30
+ const withUser = text => (os === 'linux' && draft.osUser ? `${text.replace('&& bash install.sh', '&& sudo bash install.sh')} --os-user=${draft.osUser}` : text)
31
+ const advanced = draft.home || draft.root || draft.osUser
32
+ return `<fieldset class="am-agents"><legend>${esc(T.amAgents)}</legend>${['claude', 'codex', 'grok'].map(a => `<label class="am-agent${draft.agents.includes(a) ? ' on' : ''}"><input type="checkbox" data-agentpick="${a}" ${draft.agents.includes(a) ? 'checked' : ''}>${agentMark({ agent: a })}<span><b>${esc(T.agentName[a])}</b><span>${esc(T.amAgentHint[a])}</span></span></label>`).join('')}</fieldset>
33
+ ${draft.agents.length ? '' : `<p class="am-note am-warn">${esc(T.amAgentsNone)}</p>`}
34
+ <div class="am-os"><span>${esc(T.osPick)}</span><span class="seg" role="group" aria-label="${esc(T.osPick)}">${['linux', 'macos', 'windows'].map(o => `<button type="button" data-os="${o}" aria-pressed="${o === os}"${o === os ? ' class="on"' : ''}>${{ linux: 'Linux', macos: 'macOS', windows: 'Windows' }[o]}</button>`).join('')}</span></div>
35
+ <p class="am-run">${T.runOn(os)}</p>${cmdRow(withUser(String(r.install?.[os] ?? '') + extra))}
36
+ <p class="am-note">${T.runWhat}${os === 'windows' ? ` ${T.windowsNote}` : ''}</p>
37
+ ${insecure ? `<p class="am-note am-warn">${esc(T.httpWarn)}</p>` : ''}
38
+ <p class="am-note">${esc(T.codeValid(hhmm(r.expires_at)))}</p>
39
+ <details class="am-adv"${advanced ? ' open' : ''}><summary>${esc(T.amAdvanced)}</summary>
40
+ ${os === 'linux' ? `<label class="field"><span>${T.osUser}</span><input type="text" data-osuser value="${esc(draft.osUser)}" maxlength="32" autocomplete="off"><span class="hint">${T.osUserHint}</span></label>` : ''}
41
+ <label class="check"><input type="checkbox" data-home ${draft.home ? 'checked' : ''}> <span>${T.allowHome}</span></label>
42
+ ${os === 'macos' ? '' : `<label class="check"><input type="checkbox" data-root ${draft.root ? 'checked' : ''}> <span>${T.allowRoot}</span></label>`}
43
+ ${os === 'windows' ? '' : `<p class="am-note">${T.manualCmd}</p>${cmdRow(String(r.command ?? '') + (draft.home ? ' --allow-home' : '') + (insecure ? ' --insecure' : ''))}`}
44
+ </details>`
45
+ }
46
+
47
+ function connectHtml() {
48
+ if (draft.joined) return `<p class="am-wait ok" role="status"><span class="dot ok" aria-hidden="true"></span><span>${T.machineJoined(esc(draft.joined.name)).replace(/^✓\s*/, '')}</span></p>`
49
+ if (expired()) return `<p class="am-wait bad" role="status">${esc(T.amExpired)}</p><button type="button" class="btn" data-again>${esc(T.amAnother)}</button>`
50
+ return `<p class="am-wait" role="status"><span class="dot info pulse" aria-hidden="true"></span><span>${esc(T.waitingMachine)}</span></p>${draft.slow ? `<p class="am-note">${esc(T.amSlow)}</p>` : ''}`
51
+ }
52
+
53
+ function readyHtml() {
54
+ const h = hosts.get(draft.joined.id) ?? draft.joined
55
+ const login = { claude: 'claude', codex: 'codex login', grok: 'grok login' }
56
+ return `<p class="am-note">${esc(T.amSignIn)}</p><ul class="am-signin">${(draft.agents.length ? draft.agents : ['claude']).map(a => `<li>${agentMark({ agent: a })}<code>${login[a]}</code></li>`).join('')}</ul>
57
+ <p class="am-note">${esc(T.amThenFolders)}</p>
58
+ <div class="card am-folders"><b>${esc(T.amFolders)}</b><div>${folderChips(h)}</div></div>
59
+ <div class="nt-actions">${can('operator') ? `<button type="button" class="btn" data-amsession>${esc(T.newSession)}</button><a class="btn primary" href="#/new" data-amdone>${esc(T.amNewTeam)}</a>` : `<a class="btn primary" href="#/hosts" data-amdone>${esc(T.amToMachines)}</a>`}</div>`
60
+ }
61
+
62
+ export function renderAddMachine() {
63
+ draft ??= fresh()
64
+ const box = $('addmachine')
65
+ // (Typing in a field of the page: redrawn around it, never over it.)
66
+ const keep = document.activeElement?.closest?.('#addmachine') ? document.activeElement.dataset?.osuser !== undefined ? 'osuser' : document.activeElement.name : null
67
+ const made = !!draft.enroll
68
+ const joined = !!draft.joined
69
+ const ready = joined && !!(hosts.get(draft.joined.id) ?? draft.joined).info?.folders?.length
70
+ box.innerHTML = `<div class="nt am">
71
+ <ol class="nt-steps" aria-label="${esc(T.addTitle)}">${step(1, made, T.amNameStep)}${step(2, made && joined, T.amInstallStep)}${step(3, joined, T.amConnectStep)}${step(4, ready, T.amReadyStep)}</ol>
72
+ <section class="nt-sec"><h2>${esc(T.amNameStep)}</h2><p class="am-note am-intro">${esc(T.addIntro)}</p>
73
+ <label class="field"><span>${esc(T.machineName)}</span><input type="text" name="amname" maxlength="40" value="${esc(draft.name)}" placeholder="${esc(T.machineNameHint)}" autocomplete="off" ${made ? 'disabled' : ''}></label>
74
+ <label class="check"><input type="checkbox" name="amplugin" ${draft.plugin ? 'checked' : ''} ${made ? 'disabled' : ''}> <span>${T.configurePlugin}</span></label>
75
+ ${draft.error ? `<p class="nt-issues" role="alert">${esc(draft.error)}</p>` : ''}
76
+ ${made ? '' : `<div class="nt-actions"><button type="button" class="btn primary" data-gen ${draft.generating ? 'disabled' : ''}>${esc(T.generate)}</button></div>`}
77
+ </section>
78
+ <section class="nt-sec${made ? '' : ' later'}"${made ? '' : ' aria-disabled="true"'}><h2>${esc(T.amInstallStep)}</h2>${made ? installHtml() : `<p class="am-note">${esc(T.amInstallLater)}</p>`}</section>
79
+ <section class="nt-sec${made ? '' : ' later'}"><h2>${esc(T.amConnectStep)}</h2>${made ? connectHtml() : `<p class="am-note">${esc(T.amConnectLater)}</p>`}</section>
80
+ <section class="nt-sec${joined ? '' : ' later'}" data-ready><h2>${esc(T.amReadyStep)}</h2>${joined ? readyHtml() : `<p class="am-note">${esc(T.amReadyLater)}</p>`}</section>
81
+ </div>`
82
+ if (keep === 'osuser') box.querySelector('[data-osuser]')?.focus()
83
+ else if (keep) box.querySelector(`[name="${keep}"]`)?.focus()
84
+ else if (!made && currentRoute().view === 'addmachine' && !document.activeElement?.closest?.('#addmachine')) box.querySelector('[name=amname]')?.focus({ preventScroll: true })
85
+ }
86
+ export const refreshAddMachine = () => { if (currentRoute().view === 'addmachine' && !$('addmachine').hidden) renderAddMachine() }
87
+ // Done with it (a session or team opened from it, or cancelled): the next visit starts afresh.
88
+ export const forgetAddMachine = () => { clearTimeout(draft?.slowTimer); draft = null }
89
+
90
+ async function generate() {
91
+ draft.generating = true
92
+ draft.error = ''
93
+ renderAddMachine()
94
+ try {
95
+ draft.enroll = await postJson('/api/hosts/enroll', { name: draft.name.trim(), configure_plugin: draft.plugin })
96
+ draft.joined = null
97
+ draft.slow = false
98
+ clearTimeout(draft.slowTimer)
99
+ // A minute without it: some help, where the waiting is.
100
+ const mine = draft
101
+ draft.slowTimer = setTimeout(() => { if (draft === mine && !mine.joined) { mine.slow = true; refreshAddMachine() } }, 60_000)
102
+ } catch (err) { draft.error = err.message }
103
+ draft.generating = false
104
+ renderAddMachine()
105
+ $('addmachine').querySelector('.cmd')?.closest('section')?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
106
+ }
107
+
108
+ // The machine that used this page's code (only that one) connected.
109
+ hostListeners.add(h => {
110
+ if (draft?.joined && h.id === draft.joined.id) return refreshAddMachine() // its folders, as they change
111
+ if (!draft?.enroll || draft.joined || h.removed || !h.online || h.enrollment !== draft.enroll.enrollment) return
112
+ draft.joined = h
113
+ clearTimeout(draft.slowTimer)
114
+ refreshAddMachine()
115
+ $('addmachine').querySelector('[data-ready]')?.scrollIntoView({ block: 'start', behavior: 'smooth' })
116
+ })
117
+ document.addEventListener('click', e => { if (e.target.closest?.('[data-amcancel]')) forgetAddMachine() })
118
+
119
+ const box = $('addmachine')
120
+ box.addEventListener('input', e => {
121
+ if (e.target.name === 'amname') draft.name = e.target.value
122
+ })
123
+ box.addEventListener('change', e => {
124
+ const t = e.target
125
+ if (t.name === 'amplugin') draft.plugin = t.checked
126
+ else if (t.matches('[data-agentpick]')) { const a = t.dataset.agentpick; draft.agents = t.checked ? [...new Set([...draft.agents, a])] : draft.agents.filter(x => x !== a); renderAddMachine() }
127
+ else if (t.matches('[data-home]')) { draft.home = t.checked; renderAddMachine() }
128
+ else if (t.matches('[data-root]')) { draft.root = t.checked; renderAddMachine() }
129
+ else if (t.matches('[data-osuser]')) { draft.osUser = /^[a-z_][a-z0-9_-]{0,31}$/.test(t.value) ? t.value : ''; renderAddMachine() }
130
+ })
131
+ box.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.name === 'amname' && !draft.enroll) { e.preventDefault(); void generate() } })
132
+ box.addEventListener('click', async e => {
133
+ const t = e.target
134
+ if (t.closest('[data-gen]')) return generate()
135
+ if (t.closest('[data-again]')) { draft.enroll = null; return generate() }
136
+ const os = t.closest('[data-os]')
137
+ if (os) { draft.os = os.dataset.os; return renderAddMachine() }
138
+ const copy = t.closest('[data-copy]')
139
+ if (copy) {
140
+ const pre = copy.parentElement.querySelector('.cmd')
141
+ try { await navigator.clipboard.writeText(pre.textContent); copy.textContent = T.copied } catch {
142
+ const range = document.createRange(); range.selectNodeContents(pre)
143
+ getSelection().removeAllRanges(); getSelection().addRange(range)
144
+ }
145
+ return
146
+ }
147
+ const add = t.closest('[data-hact="addfolder"]')
148
+ if (add) return addFolderDialog(add.dataset.h, refreshAddMachine)
149
+ if (t.closest('[data-amsession]')) { const id = draft.joined.id; forgetAddMachine(); location.hash = '#/hosts'; return newSessionDialog(id) }
150
+ if (t.closest('[data-amdone]')) forgetAddMachine()
151
+ })
package/ui/api.js ADDED
@@ -0,0 +1,20 @@
1
+ import { state } from './state.js'
2
+
3
+ // What the dashboard asks about, in the company it shows: /api/state is that company's.
4
+ export const inCompany = path => (path.startsWith('/api/') ? `/api/c/${encodeURIComponent(state.company)}/${path.slice('/api/'.length)}` : path)
5
+
6
+ export async function api(path) {
7
+ const r = await fetch(inCompany(path))
8
+ if (r.status === 401) throw Object.assign(new Error('unauthorized'), { status: 401 })
9
+ const j = await r.json().catch(() => ({ ok: false, description: `HTTP ${r.status}` }))
10
+ if (!j.ok) throw Object.assign(new Error(j.description), { status: j.error_code ?? r.status })
11
+ return j.result
12
+ }
13
+
14
+ // About the server, not one company: signing in, companies, users.
15
+ export async function call(path, body, headers = {}) {
16
+ const r = await fetch(path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) })
17
+ const j = await r.json().catch(() => ({ ok: false, description: `HTTP ${r.status}` }))
18
+ if (!j.ok) throw Object.assign(new Error(j.description), { status: j.error_code ?? r.status })
19
+ return j.result
20
+ }
package/ui/app.js ADDED
@@ -0,0 +1,143 @@
1
+ import { $, store } from './dom.js'
2
+ import { T, LANG } from './i18n.js'
3
+ import { state, sessions, hosts, switchCompany } from './state.js'
4
+ import { esc } from './format.js'
5
+ import { begin, loginScreen, noCompany, signOut } from './signin.js'
6
+ import { openSettings } from './people.js'
7
+ import { openPalette } from './palette.js'
8
+ import { themeNow, toggleTheme, onTheme } from './theme.js'
9
+ import { icon } from './icons.js'
10
+ import { clearMosaic } from './router.js'
11
+ import { closeMenu } from './dialogs.js'
12
+ import { termLink } from './terminal.js'
13
+ import { connect } from './stream.js'
14
+ import './format.js'
15
+ import './content.js'
16
+ import './chat.js'
17
+ import './nav.js'
18
+ import './topbar.js'
19
+ import './mosaic.js'
20
+ import './machines.js'
21
+ import './squads.js'
22
+ import './org.js'
23
+
24
+ export let serverVersion = null // (from /health and the stream)
25
+
26
+ // The dashboard is only built after the server says the sign-in is finished.
27
+ function show(id) { for (const x of ['splash', 'login', 'app']) $(x).hidden = x !== id }
28
+
29
+ // Out of the dashboard, with nothing of it left on the page. (err: why, on the sign-in page.)
30
+ export function showLogin(err = '') {
31
+ state.streamGen++
32
+ state.streamAbort?.abort()
33
+ // (Open dialogs go too: an enrollment command isn't left over the login page.)
34
+ for (const m of document.querySelectorAll('.modal-bg')) { try { m.onclose?.() } catch {} ; m.remove() }
35
+ clearMosaic()
36
+ state.sessionView?.destroy(); state.sessionView = null
37
+ state.termView?.destroy(); state.termView = null
38
+ termLink.close()
39
+ sessions.clear()
40
+ hosts.clear()
41
+ closeMenu()
42
+ state.me = null
43
+ show('login')
44
+ loginScreen(err)
45
+ }
46
+
47
+ // A finished sign-in: into the company in the address, or the last one here, if
48
+ // this user is in it. Otherwise the page loads again for one they are in.
49
+ function enter(me) {
50
+ const here = me.companies.find(c => c.id === state.company)
51
+ if (!here) {
52
+ const first = me.companies[0]
53
+ if (!first) {
54
+ // (An owner whose only company is waiting to be deleted can still bring it back.)
55
+ if (!me.user.is_platform_admin && !me.deleting?.length) { show('login'); return noCompany() }
56
+ state.me = me
57
+ show('app')
58
+ return openSettings()
59
+ }
60
+ store.set('pishaCompany', first.id)
61
+ location.replace(`?company=${encodeURIComponent(first.id)}${location.hash}`)
62
+ return
63
+ }
64
+ state.me = me
65
+ state.role = here.role
66
+ store.set('pishaCompany', here.id)
67
+ document.body.dataset.role = here.role
68
+ // The company: a choice when there are several, its name otherwise.
69
+ const select = $('companySelect')
70
+ $('companyBox').hidden = me.companies.length < 2
71
+ select.innerHTML = me.companies.map(c => `<option value="${esc(c.id)}">${esc(c.name)}</option>`).join('')
72
+ select.value = here.id
73
+ $('companyName').hidden = true // (one company: nothing to tell apart)
74
+ $('companyName').textContent = here.name ?? ''
75
+ show('app')
76
+ connect()
77
+ }
78
+
79
+ $('companySelect').addEventListener('change', e => switchCompany(e.target.value))
80
+
81
+ export async function logOut() {
82
+ await signOut()
83
+ store.set('pishaSignedOut', String(Date.now()))
84
+ showLogin()
85
+ }
86
+ $('settingsBtn').addEventListener('click', () => openSettings())
87
+ $('searchBtn').addEventListener('click', () => openPalette())
88
+
89
+ // static texts
90
+ const mac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent)
91
+ $('splash').textContent = T.connecting
92
+ $('connText').textContent = T.connecting
93
+ $('rail').setAttribute('aria-label', T.railLabel)
94
+ $('nav').setAttribute('aria-label', T.mainNav)
95
+ $('companyLabel').textContent = T.company
96
+ $('searchBtn').innerHTML = `${icon('search')}<span>${esc(T.goTo)}</span><kbd>${esc(T.searchShortcut(mac))}</kbd>`
97
+ $('settingsBtn').innerHTML = `${icon('settings')}<span>${esc(T.settings)}</span>`
98
+
99
+ // The sign-in page's own switches. (The button shows the mode it switches to.)
100
+ function themeButtons() {
101
+ const dark = themeNow() === 'dark'
102
+ for (const b of document.querySelectorAll('[data-theme-toggle]')) {
103
+ b.innerHTML = icon(dark ? 'sun' : 'moon')
104
+ b.title = dark ? T.lightMode : T.darkMode
105
+ b.setAttribute('aria-label', b.title)
106
+ }
107
+ }
108
+ for (const b of document.querySelectorAll('[data-theme-toggle]')) b.addEventListener('click', toggleTheme)
109
+ onTheme(themeButtons)
110
+ themeButtons()
111
+ for (const b of document.querySelectorAll('[data-lang]')) {
112
+ b.classList.toggle('on', b.dataset.lang === LANG)
113
+ b.addEventListener('click', () => { store.set('pishaLang', b.dataset.lang); location.reload() })
114
+ }
115
+
116
+ // Ctrl+K (⌘K on a Mac) from anywhere in the dashboard.
117
+ document.addEventListener('keydown', e => {
118
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k' && state.me && !$('app').hidden) {
119
+ e.preventDefault()
120
+ openPalette()
121
+ }
122
+ })
123
+
124
+ // "0.0.2" < "0.0.3" (numeric parts).
125
+ export const olderThan = (a, b) => {
126
+ const x = String(a).split('.').map(n => parseInt(n, 10)), y = String(b).split('.').map(n => parseInt(n, 10))
127
+ if ([...x, ...y].some(Number.isNaN)) return false
128
+ for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0)
129
+ return false
130
+ }
131
+ export function setVersion(v) {
132
+ serverVersion = v
133
+ for (const el of document.querySelectorAll('.ver')) el.textContent = T.version(v)
134
+ }
135
+ fetch('/health').then(r => r.json()).then(j => { if (j.version) setVersion(j.version) }).catch(() => {})
136
+
137
+ // Logged out in another tab of this browser: this one too.
138
+ window.addEventListener('storage', e => { if (e.key === 'pishaSignedOut' && state.me) showLogin() })
139
+
140
+ // boot (what older versions kept in this browser goes: it was the server token)
141
+ store.del('pishaToken'); store.del('swarmToken')
142
+ show('splash')
143
+ begin(enter).then(() => { if (!state.me && $('app').hidden) show('login') }, err => { show('login'); loginScreen(T.cannotConnect(err.message)) })
@@ -0,0 +1,78 @@
1
+ import { store } from './dom.js'
2
+ import { T } from './i18n.js'
3
+ import { state } from './state.js'
4
+
5
+ // Telling the user something reached their inbox while they look elsewhere:
6
+ // the count in the tab's title and on the installed app's icon, and, if they
7
+ // asked for it in Settings, a notice from the system (with a sound, if they
8
+ // like) while the dashboard is not in view. Only while it is open somewhere:
9
+ // with the browser closed, nothing (that would need push notifications).
10
+
11
+ const BASE_TITLE = document.title || 'Pisha'
12
+ let shownCount = -1
13
+
14
+ // What waits on the user, as the sidebar counts it.
15
+ const openItems = () => state.inbox.filter(i => !i.resolved_at)
16
+
17
+ export function showCount() {
18
+ const n = openItems().length
19
+ if (n === shownCount) return
20
+ shownCount = n
21
+ document.title = n ? `(${n > 99 ? '99+' : n}) ${BASE_TITLE}` : BASE_TITLE
22
+ try {
23
+ if (n) navigator.setAppBadge?.(n)?.catch?.(() => {})
24
+ else navigator.clearAppBadge?.()?.catch?.(() => {})
25
+ } catch { /* (not an installed app, or not this browser) */ }
26
+ }
27
+
28
+ // The user's choice, in this browser and for every company (it is about
29
+ // this device): off, on, or on with a sound.
30
+ export const NOTIFY = ['off', 'on', 'sound']
31
+ export const notifyChoice = () => (NOTIFY.includes(store.get('pishaNotify')) ? store.get('pishaNotify') : 'off')
32
+ export const notifySupported = () => typeof Notification === 'function'
33
+ export async function setNotify(choice) {
34
+ if (!NOTIFY.includes(choice)) return notifyChoice()
35
+ if (choice !== 'off' && notifySupported() && Notification.permission === 'default') await Notification.requestPermission().catch(() => {})
36
+ store.set('pishaNotify', choice)
37
+ return choice
38
+ }
39
+ export const notifyBlocked = () => notifySupported() && Notification.permission === 'denied'
40
+
41
+ // Which open entries the dashboard has already seen (null: none yet, the
42
+ // first list is what was there, not what arrived).
43
+ let known = null
44
+ export function inboxArrived() {
45
+ const open = openItems()
46
+ const fresh = known ? open.filter(i => !known.has(i.id)) : []
47
+ known = new Set(open.map(i => i.id))
48
+ showCount()
49
+ if (!fresh.length || notifyChoice() === 'off' || !notifySupported() || Notification.permission !== 'granted') return
50
+ if (document.visibilityState === 'visible' && document.hasFocus()) return
51
+ // (One notice for several at once: the newest, and how many.)
52
+ const i = fresh[0]
53
+ const title = i.kind === 'ask' ? T.notifyAsk(i.session) : T.notifyTell(i.session)
54
+ const body = (i.text.replace(/\s+/g, ' ').slice(0, 160)) + (fresh.length > 1 ? `\n${T.notifyMore(fresh.length - 1)}` : '')
55
+ try {
56
+ const n = new Notification(title, { body, tag: `pisha-${state.company}-inbox`, icon: '/icons/icon-192.png' })
57
+ n.onclick = () => { window.focus(); location.hash = `#/inbox/i${i.id}`; n.close() }
58
+ } catch { /* (some phones only notify from a service worker) */ }
59
+ if (notifyChoice() === 'sound') chime()
60
+ }
61
+
62
+ // Two short soft notes, made here: no sound file to fetch.
63
+ function chime() {
64
+ try {
65
+ const ctx = new (window.AudioContext || window.webkitAudioContext)()
66
+ const at = ctx.currentTime
67
+ for (const [f, t] of [[880, 0], [1320, 0.12]]) {
68
+ const o = ctx.createOscillator(), g = ctx.createGain()
69
+ o.type = 'sine'; o.frequency.value = f
70
+ g.gain.setValueAtTime(0.0001, at + t)
71
+ g.gain.exponentialRampToValueAtTime(0.12, at + t + 0.02)
72
+ g.gain.exponentialRampToValueAtTime(0.0001, at + t + 0.35)
73
+ o.connect(g).connect(ctx.destination)
74
+ o.start(at + t); o.stop(at + t + 0.4)
75
+ }
76
+ setTimeout(() => ctx.close().catch(() => {}), 1000)
77
+ } catch { /* (no sound here) */ }
78
+ }
package/ui/back.js ADDED
@@ -0,0 +1,166 @@
1
+ import { $ } from './dom.js'
2
+ import { T } from './i18n.js'
3
+ import { state, sessions, hosts } from './state.js'
4
+ import { esc } from './format.js'
5
+ import { icon } from './icons.js'
6
+ import { parseRoute } from './routes.js'
7
+
8
+ // The back button in the header. It walks the browser's own history, so it
9
+ // and the phone's back gesture always agree; what it remembers of each step
10
+ // is only the address, kept for this tab, to say where back goes.
11
+ // Moving inside one place (a session's chat or terminal, one inbox entry to
12
+ // the next, the list or the org chart of the teams) replaces the step
13
+ // instead of adding one: back leaves the place, not the tab.
14
+ // With nowhere it came from (opened from a link or a notification), back goes
15
+ // one level up: a session to its team, a terminal to its machine.
16
+
17
+ const KEY = 'pishaBack'
18
+ let stack = [location.hash] // the address of each step of this tab, by its index
19
+ let at = 0
20
+
21
+ const load = () => { try { return JSON.parse(sessionStorage.getItem(KEY)) } catch { return null } }
22
+ const save = () => { try { sessionStorage.setItem(KEY, JSON.stringify({ stack, at })) } catch { /* (private window: in memory only) */ } }
23
+ const mark = () => history.replaceState({ ...(history.state ?? {}), sq: at }, '')
24
+ const stepOf = () => (Number.isInteger(history.state?.sq) && history.state.sq >= 0 ? history.state.sq : null)
25
+
26
+ // (A reload keeps both: the steps, and the index on each.)
27
+ {
28
+ const kept = load(), sq = stepOf()
29
+ if (sq !== null && Array.isArray(kept?.stack) && sq < kept.stack.length && kept.stack.every(h => typeof h === 'string')) { stack = kept.stack; at = sq; stack[at] = location.hash }
30
+ else mark()
31
+ save()
32
+ }
33
+
34
+ // A place: what back leaves, and what it skips.
35
+ export function placeKey(r) {
36
+ switch (r.view) {
37
+ case 'inbox': return r.item ? 'inbox:item' : 'inbox'
38
+ case 'teams': case 'org': return 'teams'
39
+ case 'mosaic': return r.squad ? `live:${r.squad}` : 'teams'
40
+ case 'team': return `team:${r.squad}`
41
+ case 'session': return `s:${r.name}`
42
+ case 'terminal': return `t:${r.host}/${r.term}`
43
+ case 'hosts': return r.host ? `h:${r.host}` : 'hosts'
44
+ // (One board, whichever task is open in it.)
45
+ case 'board': return `b:${r.board}`
46
+ default: return r.view
47
+ }
48
+ }
49
+ const keyOf = hash => placeKey(parseRoute(hash))
50
+
51
+ // One level up. Null: one of the main places, which the sidebar and the bar
52
+ // at the bottom already reach, and which have no back.
53
+ export function parentOf(r) {
54
+ const enc = encodeURIComponent
55
+ switch (r.view) {
56
+ case 'inbox': return r.item ? (r.tab === 'done' ? '#/inbox/done' : '#/inbox') : null
57
+ case 'teams': case 'org': return null
58
+ case 'mosaic': return r.squad ? `#/q/${enc(r.squad)}` : null
59
+ case 'hosts': return r.host ? '#/hosts' : null
60
+ case 'addmachine': return '#/hosts'
61
+ case 'boards': return null
62
+ case 'board': return r.task ? `#/b/${r.board}` : '#/boards'
63
+ case 'terminal': return `#/h/${enc(r.host)}`
64
+ case 'session': {
65
+ const s = sessions.get(r.name)
66
+ if (s?.archived_at) return '#/archived'
67
+ // (One opened here that hasn't connected yet: what its machine says.)
68
+ const t = s ? null : [...hosts.values()].flatMap(h => h.info?.terminals ?? []).find(x => x.id === r.name)
69
+ const { role, coordinator } = s ?? t ?? {}
70
+ const team = role === 'coordinator' ? r.name : role === 'worker' ? coordinator : null
71
+ return team ? `#/q/${enc(team)}` : '#/teams'
72
+ }
73
+ default: return '#/teams' // a team, a new team, the archived ones
74
+ }
75
+ }
76
+
77
+ // What a place is called, on the button.
78
+ export function placeName(hash) {
79
+ const r = parseRoute(hash)
80
+ const team = name => state.squadMeta.get(name)?.title || name
81
+ switch (r.view) {
82
+ case 'inbox': return T.inbox
83
+ case 'teams': case 'org': return T.teams
84
+ case 'mosaic': return r.squad ? T.tqLiveTitle(team(r.squad)) : T.teams
85
+ case 'team': return team(r.squad)
86
+ case 'session': return r.name
87
+ case 'terminal': return r.term
88
+ case 'hosts': return (r.host && hosts.get(r.host)?.name) || T.machines
89
+ case 'archived': return T.archived
90
+ case 'newteam': return T.newTeam
91
+ case 'addmachine': return T.addTitle
92
+ case 'boards': return T.boards
93
+ case 'board': return state.boards.find(b => b.id === r.board)?.name ?? T.boards
94
+ default: return T.leads
95
+ }
96
+ }
97
+
98
+ // Where back goes from here: some steps back in the history, or (none of
99
+ // another place) one level up in place of this one. Null: no back here.
100
+ export function backTarget() {
101
+ const r = parseRoute(location.hash)
102
+ const up = parentOf(r)
103
+ if (!up) return null
104
+ const key = placeKey(r)
105
+ for (let j = at - 1; j >= 0; j--) if (keyOf(stack[j]) !== key) return { steps: at - j, hash: stack[j] }
106
+ return { hash: up }
107
+ }
108
+
109
+ // On every change of address (router.js, before it draws the view).
110
+ export function trackNavigation() {
111
+ const sq = stepOf()
112
+ if (sq !== null && sq < stack.length) at = sq // back or forward to a step it knows
113
+ else { at += 1; stack = stack.slice(0, at); mark() }
114
+ stack[at] = location.hash
115
+ save()
116
+ }
117
+
118
+ // Another address for the step it is on: no new step.
119
+ export function replaceHash(hash) {
120
+ if (location.hash === hash) return
121
+ history.replaceState(history.state, '', hash)
122
+ stack[at] = location.hash
123
+ save()
124
+ window.dispatchEvent(new HashChangeEvent('hashchange'))
125
+ }
126
+
127
+ export function goBack() {
128
+ const t = backTarget()
129
+ if (!t) return
130
+ if (t.steps) history.go(-t.steps)
131
+ else replaceHash(t.hash)
132
+ }
133
+
134
+ // Closing something to where it came from (the inbox entry to its list):
135
+ // the step before when it was there, else that place in place of this one.
136
+ export function closeTo(hash) {
137
+ if (at > 0 && keyOf(stack[at - 1]) === keyOf(hash)) history.back()
138
+ else replaceHash(hash)
139
+ }
140
+
141
+ // A link to the same place, clicked: the step is replaced, not added. One
142
+ // that cancels (data-back) goes back where the user was; its address is
143
+ // where it goes when there is none.
144
+ document.addEventListener('click', e => {
145
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
146
+ const a = e.target.closest?.('a[href^="#/"]')
147
+ if (!a || a.target || !a.closest('#app')) return
148
+ const to = a.getAttribute('href')
149
+ if (a.hasAttribute('data-back')) { e.preventDefault(); return backTarget() ? goBack() : replaceHash(to) }
150
+ if (to !== location.hash && keyOf(to) === keyOf(location.hash)) { e.preventDefault(); replaceHash(to) }
151
+ })
152
+
153
+ export function renderBack() {
154
+ const b = $('backBtn')
155
+ const t = backTarget()
156
+ b.hidden = !t
157
+ if (!t) return
158
+ const name = placeName(t.hash)
159
+ const html = `${icon('chevron', 'flip')}<span class="head-back-to">${esc(name)}</span>`
160
+ if (b._html !== html) { b.innerHTML = html; b._html = html }
161
+ b.setAttribute('aria-label', T.backTo(name))
162
+ b.title = T.backTo(name)
163
+ // (The inbox shows its list beside the entry, but on a phone.)
164
+ b.classList.toggle('narrow-only', parseRoute(location.hash).view === 'inbox')
165
+ }
166
+ $('backBtn').addEventListener('click', goBack)