heyquilt 0.3.183 → 0.3.184
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.
- package/RELEASES.md +6 -0
- package/package.json +1 -1
- package/src/account.js +15 -0
- package/src/api/memory-store.js +22 -1
- package/src/api/routes/connections.js +54 -13
- package/src/api/routes/workspace-chat.js +77 -0
- package/src/api/server.js +2 -1
- package/src/api/supabase-store.js +25 -1
- package/src/app-tools.js +2 -2
- package/src/ui/app.css +15 -1
- package/src/ui/connections.js +48 -8
- package/src/ui/home.js +8 -3
- package/src/ui/project-channel.js +93 -0
- package/src/ui/project-model.js +27 -0
- package/src/ui/project-pop.js +1 -1
- package/src/ui/projects.js +81 -23
- package/src/ui/session.js +20 -6
- package/src/ui-server.js +10 -3
package/RELEASES.md
CHANGED
|
@@ -11,6 +11,12 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
|
|
|
11
11
|
Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
|
|
12
12
|
nothing else is.
|
|
13
13
|
|
|
14
|
+
## 0.3.184 — 2026-11-22
|
|
15
|
+
|
|
16
|
+
Connections for the agents you choose.
|
|
17
|
+
|
|
18
|
+
- **A connection for chosen agents.** In Connections, an app you connected can be for **People and chosen agents**: tick the agents that may use it. An agent that was not chosen does not see the app and cannot run its actions; people in the codebase always can.
|
|
19
|
+
|
|
14
20
|
## 0.3.183 — 2026-11-22
|
|
15
21
|
|
|
16
22
|
What you code in together is now called a codebase.
|
package/package.json
CHANGED
package/src/account.js
CHANGED
|
@@ -350,6 +350,21 @@ export async function moveSessionToWorkspace ({ token, id, room, api = apiUrl(),
|
|
|
350
350
|
return { session: r.session, added: Array.isArray(r.added) ? r.added : [], peopleNeedAdmin: !!r.peopleNeedAdmin }
|
|
351
351
|
}
|
|
352
352
|
|
|
353
|
+
// A project's channel (routes/workspace-chat.js): its messages, saying something, and marking it read.
|
|
354
|
+
export async function workspaceMessages ({ token, id, after = 0, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
355
|
+
const r = await call(fetchImpl, api, 'GET', `${ws$(id)}/messages${after ? `?after=${encodeURIComponent(after)}` : ''}`, null, token)
|
|
356
|
+
if (!Array.isArray(r.messages)) throw new Error(BAD_REPLY)
|
|
357
|
+
return r
|
|
358
|
+
}
|
|
359
|
+
export async function sayInWorkspace ({ token, id, text, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
360
|
+
const r = await call(fetchImpl, api, 'POST', `${ws$(id)}/messages`, { text }, token)
|
|
361
|
+
if (!r.message) throw new Error(BAD_REPLY)
|
|
362
|
+
return r
|
|
363
|
+
}
|
|
364
|
+
export async function readWorkspaceMessages ({ token, id, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
365
|
+
return call(fetchImpl, api, 'POST', `${ws$(id)}/messages/read`, {}, token)
|
|
366
|
+
}
|
|
367
|
+
|
|
353
368
|
// Workspace invites: an admin invites a person ({ account } or { email }); they accept in their Quilt.
|
|
354
369
|
export async function listWorkspaceInvites ({ token, id, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
355
370
|
const r = await call(fetchImpl, api, 'GET', `${ws$(id)}/invites`, null, token)
|
package/src/api/memory-store.js
CHANGED
|
@@ -62,6 +62,7 @@ export function createMemoryStore ({ now = Date.now } = {}) {
|
|
|
62
62
|
const secretTickets = new Map(); const secretRuns = new Map(); const secretAsks = new Map(); const secretUses = []
|
|
63
63
|
// App connections (20261112000000_app_connections.sql).
|
|
64
64
|
const appConnections = new Map(); const appCalls = new Map()
|
|
65
|
+
const workspaceMessages = new Map(); const workspaceReads = new Map() // a project's channel, and each account's place in it
|
|
65
66
|
const scopeKey = (scopeType, scopeId) => `${scopeType}\n${scopeId}`
|
|
66
67
|
// A secret as the API's routes see it: never its sealed value (secretSealed reads that, for the vault).
|
|
67
68
|
const secretMeta = (r) => { if (!r) return null; const { sealedValue, ...rest } = copy(r); return rest }
|
|
@@ -989,6 +990,8 @@ export function createMemoryStore ({ now = Date.now } = {}) {
|
|
|
989
990
|
for (const s of relaySessions.values()) if (s.workspaceId === id) s.workspaceId = null
|
|
990
991
|
for (const [k, m] of workspaceMembers) if (m.workspaceId === id) workspaceMembers.delete(k)
|
|
991
992
|
for (const [k, i] of workspaceInvites) if (i.workspaceId === id) workspaceInvites.delete(k)
|
|
993
|
+
for (const [k, m] of workspaceMessages) if (m.workspaceId === id) workspaceMessages.delete(k)
|
|
994
|
+
for (const k of [...workspaceReads.keys()]) if (k.startsWith(`${id}|`)) workspaceReads.delete(k)
|
|
992
995
|
for (const [k, f] of workspaceFiles) {
|
|
993
996
|
if (f.workspaceId !== id) continue
|
|
994
997
|
for (const vk of [...workspaceFileVersions.keys()]) if (vk.startsWith(`${f.id}\n`)) workspaceFileVersions.delete(vk)
|
|
@@ -1296,10 +1299,28 @@ export function createMemoryStore ({ now = Date.now } = {}) {
|
|
|
1296
1299
|
return secretUses.filter((u) => secretIds.includes(u.secretId)).sort((a, b) => b.at - a.at).slice(0, limit).map(copy)
|
|
1297
1300
|
},
|
|
1298
1301
|
|
|
1302
|
+
// A project's channel (20261122010000_project_channel.sql): its messages, and what each account has read.
|
|
1303
|
+
async addWorkspaceMessage ({ workspaceId, account, name = '', text }) {
|
|
1304
|
+
if (!workspaces.has(workspaceId)) throw fkViolation('workspace', 'does not exist')
|
|
1305
|
+
// Two messages never share a time: the order they were written in is the order they are read in.
|
|
1306
|
+
const last = Math.max(0, ...all(workspaceMessages, (m) => m.workspaceId === workspaceId).map((m) => m.createdAt))
|
|
1307
|
+
const row = { id: uuid(), workspaceId, account, name, text, createdAt: Math.max(now(), last + 1) }
|
|
1308
|
+
workspaceMessages.set(row.id, row); return copy(row)
|
|
1309
|
+
},
|
|
1310
|
+
async listWorkspaceMessages (workspaceId, { after = 0, limit = 100 } = {}) {
|
|
1311
|
+
const mine = all(workspaceMessages, (m) => m.workspaceId === workspaceId && m.createdAt > after).sort((a, b) => a.createdAt - b.createdAt)
|
|
1312
|
+
return (after ? mine.slice(0, limit) : mine.slice(-limit)).map(copy)
|
|
1313
|
+
},
|
|
1314
|
+
async countWorkspaceMessages (workspaceId, { after = 0, notBy = '' } = {}) {
|
|
1315
|
+
return all(workspaceMessages, (m) => m.workspaceId === workspaceId && m.createdAt > after && m.account !== notBy).length
|
|
1316
|
+
},
|
|
1317
|
+
async workspaceReadAt (workspaceId, account) { return workspaceReads.get(`${workspaceId}|${account}`) || 0 },
|
|
1318
|
+
async setWorkspaceReadAt (workspaceId, account, at) { workspaceReads.set(`${workspaceId}|${account}`, Math.max(at, workspaceReads.get(`${workspaceId}|${account}`) || 0)) },
|
|
1319
|
+
|
|
1299
1320
|
// App connections (20261112000000_app_connections.sql): Composio holds the tokens.
|
|
1300
1321
|
async addAppConnection (c) {
|
|
1301
1322
|
if (all(appConnections, (r) => r.composioId === c.composioId).length) throw duplicate('connection')
|
|
1302
|
-
const row = { id: uuid(), appName: '', logo: '', status: 'pending', who: 'all', ...copy(c), createdAt: now(), updatedAt: now() }
|
|
1323
|
+
const row = { id: uuid(), appName: '', logo: '', status: 'pending', who: 'all', agents: [], ...copy(c), createdAt: now(), updatedAt: now() }
|
|
1303
1324
|
appConnections.set(row.id, row)
|
|
1304
1325
|
return copy(row)
|
|
1305
1326
|
},
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
// App connections (plans/app-connections.md): apps a team, workspace or
|
|
1
|
+
// App connections (plans/app-connections.md): apps a team, workspace, session or person connected through
|
|
2
2
|
// Composio (composio.js), and the agents' use of them (quilt_apps, quilt_app_tools, quilt_app_call
|
|
3
3
|
// in app-tools.js). People connect at a scope, as with secrets; Composio holds the tokens. An
|
|
4
4
|
// action that only reads runs at once; anything else waits for a person in the session, whose
|
|
5
5
|
// approval runs it once. Every call is kept (app_calls): the approvals, the session's record of
|
|
6
6
|
// what agents did in other apps, and the daily cap.
|
|
7
|
+
// A person's own connections (scope 'account') reach every project that person owns and their
|
|
8
|
+
// codebases in no project. A connection is for people and agents ('all'), people only, or only
|
|
9
|
+
// the agents chosen for it ('agents', with their ids).
|
|
7
10
|
import { HttpError, Raw, needId } from '../http.js'
|
|
8
11
|
import { orgAccess } from '../org-access.js'
|
|
9
12
|
import { workspaceReach } from '../workspace-reach.js'
|
|
@@ -12,7 +15,11 @@ import { sessionMember, roomLevels, workspaceLevels, LEVEL_WORDS } from '../secr
|
|
|
12
15
|
import { composioUser } from '../composio.js'
|
|
13
16
|
|
|
14
17
|
const ROOM = /^[A-Za-z0-9_-]{1,64}$/
|
|
15
|
-
const SCOPE = '(org|workspace|session)'
|
|
18
|
+
const SCOPE = '(org|workspace|session|account)'
|
|
19
|
+
const AGENT_ID = /^[0-9a-f-]{36}$/i
|
|
20
|
+
const MAX_CHOSEN = 100
|
|
21
|
+
// What each level is called (secrets have the first three; a person's own connections are for every project).
|
|
22
|
+
const WORDS = { ...LEVEL_WORDS, account: 'Every project' }
|
|
16
23
|
const APP = /^[a-z0-9_-]{1,64}$/
|
|
17
24
|
const TOOL = /^[A-Za-z0-9_-]{1,120}$/
|
|
18
25
|
const DAY_MS = 24 * 60 * 60 * 1000
|
|
@@ -61,21 +68,44 @@ export function connectionRoutes (ctx) {
|
|
|
61
68
|
return { account: `person:${p.userId}`, kind: 'person', userId: p.userId, agent: null }
|
|
62
69
|
}
|
|
63
70
|
|
|
71
|
+
/** The level of a person's own connections: theirs reach every project they own. */
|
|
72
|
+
const accountLevel = async (userId) => ({ type: 'account', id: userId, name: (await store.profile(userId))?.name || '' })
|
|
73
|
+
/** A workspace's levels for connections: itself, its team, and (a person's own project) its owner's own. */
|
|
74
|
+
async function levelsOfWorkspace (ws) {
|
|
75
|
+
const levels = await workspaceLevels(store, ws)
|
|
76
|
+
if (ws.ownerUserId) levels.push(await accountLevel(ws.ownerUserId))
|
|
77
|
+
return levels
|
|
78
|
+
}
|
|
79
|
+
/** A session's levels for connections: as for secrets, then the own connections of whoever owns its project, or owns it when it is in none. */
|
|
80
|
+
async function levelsOfRoom (room) {
|
|
81
|
+
const found = await roomLevels(store, room)
|
|
82
|
+
if (!found) return null
|
|
83
|
+
const ws = found.session.workspaceId ? await store.workspaceById(found.session.workspaceId) : null
|
|
84
|
+
const owner = ws ? ws.ownerUserId : String(found.session.ownerAccount || '').startsWith('person:') ? found.session.ownerAccount.slice(7) : null
|
|
85
|
+
return owner ? { ...found, levels: [...found.levels, await accountLevel(owner)] } : found
|
|
86
|
+
}
|
|
87
|
+
|
|
64
88
|
/** One scope as a person reaches it, as for secrets: { type, id, name, levels, canManage, me }. */
|
|
65
89
|
async function scopeOf (req, type, rawId) {
|
|
66
90
|
const me = await whoCalls(req)
|
|
67
91
|
if (me.kind !== 'person') throw new HttpError(403, 'People connect apps; agents use them with quilt_app_call.')
|
|
92
|
+
if (type === 'account') {
|
|
93
|
+
// Only your own: "me", or your own id.
|
|
94
|
+
if (rawId !== 'me' && rawId !== me.userId) throw new HttpError(404, 'no such account')
|
|
95
|
+
const level = await accountLevel(me.userId)
|
|
96
|
+
return { type, id: me.userId, name: level.name, levels: [level], canManage: true, me }
|
|
97
|
+
}
|
|
68
98
|
if (type === 'org') {
|
|
69
99
|
const a = await orgAccess(store, me.userId, rawId)
|
|
70
100
|
return { type, id: a.org.id, name: a.org.name, levels: [{ type, id: a.org.id, name: a.org.name }], canManage: a.can('org', 'u'), me }
|
|
71
101
|
}
|
|
72
102
|
if (type === 'workspace') {
|
|
73
103
|
const r = await reach(req, needId(rawId, 'project'))
|
|
74
|
-
return { type, id: r.ws.id, name: r.ws.name, levels: await
|
|
104
|
+
return { type, id: r.ws.id, name: r.ws.name, levels: await levelsOfWorkspace(r.ws), canManage: !!r.access.admin, me }
|
|
75
105
|
}
|
|
76
106
|
const room = String(rawId)
|
|
77
107
|
if (!ROOM.test(room)) throw new HttpError(404, 'no such codebase')
|
|
78
|
-
const found = await
|
|
108
|
+
const found = await levelsOfRoom(room)
|
|
79
109
|
if (!found || !(await sessionMember(store, room, me.account))) throw new HttpError(404, 'no such codebase')
|
|
80
110
|
// Anyone in the session connects apps for it (the owner removes any; others their own).
|
|
81
111
|
return { type, id: room, name: found.session.name || '', levels: found.levels, canManage: true, owner: found.session.ownerAccount === me.account, me, session: found.session }
|
|
@@ -95,10 +125,22 @@ export function connectionRoutes (ctx) {
|
|
|
95
125
|
}
|
|
96
126
|
|
|
97
127
|
const view = async (c, level, extra = {}) => ({
|
|
98
|
-
id: c.id, app: c.app, name: c.appName || c.app, logo: c.logo, status: c.status, who: c.who,
|
|
128
|
+
id: c.id, app: c.app, name: c.appName || c.app, logo: c.logo, status: c.status, who: c.who, agents: c.who === 'agents' ? (c.agents || []) : [],
|
|
99
129
|
level: level.type, levelName: level.name || '', by: await nameOf(c.createdBy), createdAt: c.createdAt, ...extra
|
|
100
130
|
})
|
|
101
131
|
|
|
132
|
+
/** Who may use a connection, from a request: { who, agents }. 'agents' names the agents chosen for it by id. */
|
|
133
|
+
function whoFrom (body, fallback = null) {
|
|
134
|
+
const who = body.who === undefined && fallback ? fallback : body.who
|
|
135
|
+
if (who !== 'all' && who !== 'people' && who !== 'agents') throw new HttpError(400, 'who is "all", "people" or "agents"')
|
|
136
|
+
if (who !== 'agents') return { who, agents: [] }
|
|
137
|
+
const agents = [...new Set(Array.isArray(body.agents) ? body.agents.map(String) : [])]
|
|
138
|
+
if (!agents.length || agents.length > MAX_CHOSEN || !agents.every((a) => AGENT_ID.test(a))) throw new HttpError(400, 'Say which agents may use it: agents is a list of their ids.')
|
|
139
|
+
return { who, agents }
|
|
140
|
+
}
|
|
141
|
+
/** Whether an agent may use a connection: one for everyone, or one that chose it. */
|
|
142
|
+
const agentMay = (c, agentId) => c.who === 'all' || (c.who === 'agents' && !!agentId && (c.agents || []).includes(agentId))
|
|
143
|
+
|
|
102
144
|
/** Every connection a session (or workspace) reaches, nearest level first: [{ connection, level }]. */
|
|
103
145
|
async function reachable (levels) {
|
|
104
146
|
const out = []
|
|
@@ -124,14 +166,14 @@ export function connectionRoutes (ctx) {
|
|
|
124
166
|
if (!ROOM.test(room)) throw new HttpError(404, 'no such codebase')
|
|
125
167
|
const me = await whoCalls(req)
|
|
126
168
|
if (!(await sessionMember(store, room, me.account, { agent: me.agent }))) throw new HttpError(404, 'no such codebase')
|
|
127
|
-
const found = await
|
|
169
|
+
const found = await levelsOfRoom(room)
|
|
128
170
|
if (!found) throw new HttpError(404, 'no such codebase')
|
|
129
171
|
return { me, found }
|
|
130
172
|
}
|
|
131
173
|
|
|
132
174
|
/** The connections the caller may use in the session, nearest level first. */
|
|
133
175
|
async function usable (me, found) {
|
|
134
|
-
return (await reachable(found.levels)).filter(({ connection: c }) => c.status === 'active' && (me.kind === 'person' || c.
|
|
176
|
+
return (await reachable(found.levels)).filter(({ connection: c }) => c.status === 'active' && (me.kind === 'person' || agentMay(c, me.agent && me.agent.id)))
|
|
135
177
|
}
|
|
136
178
|
|
|
137
179
|
const capKey = (session) => session.workspaceId ? `workspace:${session.workspaceId}` : `session:${session.room || ''}`
|
|
@@ -201,18 +243,17 @@ export function connectionRoutes (ctx) {
|
|
|
201
243
|
if (!APP.test(app)) throw new HttpError(400, 'Say which app to connect.')
|
|
202
244
|
const t = await composio.toolkit(app)
|
|
203
245
|
const l = await composio.link({ user: composioUser(s.type, s.id), app, callbackUrl: `${apiUrl}/v1/connections/done` })
|
|
204
|
-
const c = await store.addAppConnection({ scopeType: s.type, scopeId: s.id, app, appName: String(t.name || app).slice(0, 120), logo: String(t.logo || '').slice(0, 500), composioId: l.composioId, status: 'pending',
|
|
246
|
+
const c = await store.addAppConnection({ scopeType: s.type, scopeId: s.id, app, appName: String(t.name || app).slice(0, 120), logo: String(t.logo || '').slice(0, 500), composioId: l.composioId, status: 'pending', ...whoFrom(body, 'all'), createdBy: s.me.account })
|
|
205
247
|
return { url: l.url, connection: await view(c, s.levels[0]) }
|
|
206
248
|
}],
|
|
207
249
|
|
|
208
|
-
// Who may use it: 'all' (people and agents) or '
|
|
250
|
+
// Who may use it: 'all' (people and agents), 'people', or 'agents' with the ids of the agents chosen.
|
|
209
251
|
['PATCH', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
|
|
210
252
|
const s = await scopeOf(req, type, id)
|
|
211
253
|
const c = await store.appConnectionById(needId(cid, 'connection'))
|
|
212
254
|
if (!c || c.scopeType !== s.type || c.scopeId !== s.id) throw new HttpError(404, 'no such connection')
|
|
213
255
|
if (!mayChange(s, c)) throw new HttpError(403, 'Only whoever connected it, or the codebase\'s owner, changes it.')
|
|
214
|
-
|
|
215
|
-
return view(await store.updateAppConnection(c.id, { who: body.who }), s.levels[0])
|
|
256
|
+
return view(await store.updateAppConnection(c.id, whoFrom(body)), s.levels[0])
|
|
216
257
|
}],
|
|
217
258
|
|
|
218
259
|
['DELETE', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
|
|
@@ -267,7 +308,7 @@ export function connectionRoutes (ctx) {
|
|
|
267
308
|
const call = await store.addAppCall({ room, capKey: key, connectionId: pick.connection.id, app: t.app, tool: t.slug, args, readOnly: t.readOnly, state: 'waiting', account: me.account })
|
|
268
309
|
if (t.readOnly) return answer(await run(call, pick.connection))
|
|
269
310
|
const who = await nameOf(me.account)
|
|
270
|
-
await sayInRoom(room, { approval: call.id, text: `${who} asks to run ${t.slug} on ${pick.connection.appName || t.app} (${
|
|
311
|
+
await sayInRoom(room, { approval: call.id, text: `${who} asks to run ${t.slug} on ${pick.connection.appName || t.app} (${WORDS[pick.level.type].toLowerCase()} connection): ${argsLine(args)}. A person in the codebase approves or declines it here.` }).catch((err) => log(`connections: tell ${room}: ${err.message}`))
|
|
271
312
|
return answer(await waitFor(call.id) || call, pick.connection.appName)
|
|
272
313
|
}],
|
|
273
314
|
|
|
@@ -294,7 +335,7 @@ export function connectionRoutes (ctx) {
|
|
|
294
335
|
let ended = decided
|
|
295
336
|
if (allow) {
|
|
296
337
|
const c = call.connectionId ? await store.appConnectionById(call.connectionId) : null
|
|
297
|
-
const still = c && c.status === 'active' && (await usable(
|
|
338
|
+
const still = c && c.status === 'active' && (await usable(call.account.startsWith('person:') ? { kind: 'person' } : { kind: 'agent', agent: { id: call.account.slice('agent:'.length) } }, found)).some((x) => x.connection.id === c.id)
|
|
298
339
|
ended = still ? await run(decided, c) : (await store.updateAppCall(call.id, { state: 'failed', error: 'That connection was removed.', ranAt: now() }, { from: 'approved' })) || decided
|
|
299
340
|
}
|
|
300
341
|
const what = allow ? (ended.state === 'ran' ? 'ran it' : `it failed: ${String(ended.error || '').slice(0, 200)}`) : 'declined it'
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// A project's channel: one conversation for everyone in a project (a workspace), kept by the
|
|
2
|
+
// accounts API so people can talk with no codebase open. A codebase's own channel is its
|
|
3
|
+
// session's chat, on the relay; this is only the project's.
|
|
4
|
+
//
|
|
5
|
+
// Everyone who reaches the project reads and writes it: its people, and agents placed in it.
|
|
6
|
+
// Each account's place in it (what it has read) is kept, so the app can say how much is new.
|
|
7
|
+
import { HttpError, needId, stripInvisible } from '../http.js'
|
|
8
|
+
import { workspaceReach, canSeeFiles } from '../workspace-reach.js'
|
|
9
|
+
|
|
10
|
+
export const MAX_MESSAGE = 8000
|
|
11
|
+
const PAGE = 100
|
|
12
|
+
const PER_MINUTE = 30
|
|
13
|
+
|
|
14
|
+
export function workspaceChatRoutes (ctx) {
|
|
15
|
+
const { store, now = Date.now, workspaces = false } = ctx
|
|
16
|
+
const { reach } = workspaceReach(ctx)
|
|
17
|
+
const gated = (fn) => (...args) => {
|
|
18
|
+
if (!workspaces) throw new HttpError(404, 'not found')
|
|
19
|
+
return fn(...args)
|
|
20
|
+
}
|
|
21
|
+
const nameOf = async (account) => {
|
|
22
|
+
const [kind, id] = String(account || '').split(':')
|
|
23
|
+
const raw = kind === 'agent' ? (await store.agentById(id).catch(() => null))?.name : kind === 'person' ? (await store.profile(id))?.name : ''
|
|
24
|
+
return stripInvisible(raw || '').join('').trim()
|
|
25
|
+
}
|
|
26
|
+
const view = (m, me) => ({ id: m.id, by: m.name || 'Someone', kind: String(m.account).startsWith('agent:') ? 'agent' : 'person', mine: m.account === me, text: m.text, at: m.createdAt })
|
|
27
|
+
|
|
28
|
+
/** The project, for someone who is in it: an org member who only sees its page (Workspaces: Read alone) is not. */
|
|
29
|
+
async function inProject (req, id) {
|
|
30
|
+
const r = await reach(req, needId(id, 'project'))
|
|
31
|
+
if (!canSeeFiles(r.access)) throw new HttpError(403, 'Only people in this project read its channel.')
|
|
32
|
+
return r
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// How fast one account may write here, counted in this process: a channel is for people talking.
|
|
36
|
+
const recent = new Map()
|
|
37
|
+
function limit (account) {
|
|
38
|
+
const at = now()
|
|
39
|
+
const list = (recent.get(account) || []).filter((t) => at - t < 60_000)
|
|
40
|
+
if (list.length >= PER_MINUTE) throw new HttpError(429, 'That is a lot of messages in a minute. Wait a moment.')
|
|
41
|
+
list.push(at); recent.set(account, list)
|
|
42
|
+
if (recent.size > 5000) for (const [k, v] of recent) if (!v.some((t) => at - t < 60_000)) recent.delete(k)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return [
|
|
46
|
+
// The channel's messages, oldest first: the newest page, or what came after `after` (a time in ms).
|
|
47
|
+
// `unread`: how many others wrote since the caller last read it; `readAt`: when that was.
|
|
48
|
+
['GET', /^\/v1\/workspaces\/([^/]+)\/messages$/, gated(async (req, body, [id], url) => {
|
|
49
|
+
const { me, ws } = await inProject(req, id)
|
|
50
|
+
const u = url || new URL(req.url, 'http://x')
|
|
51
|
+
const after = Number(u.searchParams.get('after')) || 0
|
|
52
|
+
const messages = await store.listWorkspaceMessages(ws.id, { after, limit: PAGE })
|
|
53
|
+
const readAt = await store.workspaceReadAt(ws.id, me.account)
|
|
54
|
+
return { messages: messages.map((m) => view(m, me.account)), readAt, unread: await store.countWorkspaceMessages(ws.id, { after: readAt, notBy: me.account }) }
|
|
55
|
+
})],
|
|
56
|
+
|
|
57
|
+
['POST', /^\/v1\/workspaces\/([^/]+)\/messages$/, gated(async (req, body, [id]) => {
|
|
58
|
+
const { me, ws } = await inProject(req, id)
|
|
59
|
+
const text = String(body.text || '').replace(/\r\n/g, '\n').trim()
|
|
60
|
+
if (!text) throw new HttpError(400, 'Say something.')
|
|
61
|
+
if (text.length > MAX_MESSAGE) throw new HttpError(413, 'That message is too long.')
|
|
62
|
+
limit(me.account)
|
|
63
|
+
const m = await store.addWorkspaceMessage({ workspaceId: ws.id, account: me.account, name: await nameOf(me.account), text })
|
|
64
|
+
// Whoever writes has read up to here.
|
|
65
|
+
await store.setWorkspaceReadAt(ws.id, me.account, m.createdAt)
|
|
66
|
+
return { message: view(m, me.account) }
|
|
67
|
+
})],
|
|
68
|
+
|
|
69
|
+
// The caller has read the channel up to now.
|
|
70
|
+
['POST', /^\/v1\/workspaces\/([^/]+)\/messages\/read$/, gated(async (req, body, [id]) => {
|
|
71
|
+
const { me, ws } = await inProject(req, id)
|
|
72
|
+
const at = now()
|
|
73
|
+
await store.setWorkspaceReadAt(ws.id, me.account, at)
|
|
74
|
+
return { readAt: at }
|
|
75
|
+
})]
|
|
76
|
+
]
|
|
77
|
+
}
|
package/src/api/server.js
CHANGED
|
@@ -36,6 +36,7 @@ import { workspaceRoutes } from './routes/workspaces.js'
|
|
|
36
36
|
import { workspaceFileRoutes } from './routes/workspace-files.js'
|
|
37
37
|
import { workspaceAgentRoutes } from './routes/workspace-agents.js'
|
|
38
38
|
import { workspaceInviteRoutes } from './routes/workspace-invites.js'
|
|
39
|
+
import { workspaceChatRoutes } from './routes/workspace-chat.js'
|
|
39
40
|
import { HOSTED_RELAY } from '../settings.js'
|
|
40
41
|
import { roomAccessFrom } from './access.js'
|
|
41
42
|
import { joiningRoom, sessionArg } from '../mcp-room.js'
|
|
@@ -449,7 +450,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
449
450
|
// Always routed: with the flag off each answers a plain 404 of its own, so the app's
|
|
450
451
|
// check at every launch isn't filed as a missing route.
|
|
451
452
|
// Only these take a hosted agent's pass (workspaceReach), so they alone get the pass key.
|
|
452
|
-
routes.push(...workspaceRoutes({ ...ctx, workspaces, passKey, policyChanged }), ...workspaceInviteRoutes({ ...ctx, workspaces, passKey }), ...workspaceAgentRoutes({ ...ctx, workspaces, passKey, relayUrl, webhookFetch, webhookLookup, allowLocalWebhooks, trackDelivery, limitAnnounce }))
|
|
453
|
+
routes.push(...workspaceRoutes({ ...ctx, workspaces, passKey, policyChanged }), ...workspaceInviteRoutes({ ...ctx, workspaces, passKey }), ...workspaceChatRoutes({ ...ctx, workspaces, passKey }), ...workspaceAgentRoutes({ ...ctx, workspaces, passKey, relayUrl, webhookFetch, webhookLookup, allowLocalWebhooks, trackDelivery, limitAnnounce }))
|
|
453
454
|
const wsFiles = workspaceFileRoutes({ ...ctx, workspaces, passKey })
|
|
454
455
|
routes.push(...wsFiles.routes)
|
|
455
456
|
// Secrets (routes/secrets.js): off until the vault is set up (QUILT_VAULT_SECRET).
|
|
@@ -52,7 +52,8 @@ const SECRET_RUN = 'id, token_hash, room, account, kind, label, created_at, expi
|
|
|
52
52
|
const SECRET_ASK = 'run_id, secret_id, name, state, asked_at, answered_at'
|
|
53
53
|
const SECRET_USE = 'id, secret_id, run_id, room, account, upstream, at'
|
|
54
54
|
// App connections (20261112000000_app_connections.sql).
|
|
55
|
-
const
|
|
55
|
+
const WORKSPACE_MESSAGE = 'id, workspace_id, account, name, text, created_at'
|
|
56
|
+
const APP_CONNECTION = 'id, scope_type, scope_id, app, app_name, logo, composio_id, status, who, agents, created_by, created_at, updated_at'
|
|
56
57
|
const APP_CALL = 'id, room, cap_key, connection_id, app, tool, args, read_only, state, account, decided_by, result, error, created_at, decided_at, ran_at'
|
|
57
58
|
// How Quilt wakes each agent (20261025000000_agent_wake.sql).
|
|
58
59
|
const AGENT_WAKE = 'agent_id, method, detail, pending, updated_at'
|
|
@@ -503,6 +504,29 @@ export function createSupabaseStore ({ url, serviceKey, client, fetch: authFetch
|
|
|
503
504
|
.insert({ workspace_id: workspaceId, email, account, account_name: accountName, access, invited_by: invitedBy, expires_at: ts(expiresAt) })
|
|
504
505
|
.select(WORKSPACE_INVITE).single()))
|
|
505
506
|
},
|
|
507
|
+
// A project's channel (20261122010000_project_channel.sql).
|
|
508
|
+
async addWorkspaceMessage ({ workspaceId, account, name = '', text }) {
|
|
509
|
+
return rowFrom(await one(db.from('workspace_messages').insert({ workspace_id: workspaceId, account, name, text }).select(WORKSPACE_MESSAGE).single()))
|
|
510
|
+
},
|
|
511
|
+
async listWorkspaceMessages (workspaceId, { after = 0, limit = 100 } = {}) {
|
|
512
|
+
const q = db.from('workspace_messages').select(WORKSPACE_MESSAGE).eq('workspace_id', workspaceId)
|
|
513
|
+
// What came after a time, oldest first; with no time, the newest page (read back into the order it was written in).
|
|
514
|
+
if (after) return (await one(q.gt('created_at', ts(after)).order('created_at').limit(limit))).map(rowFrom)
|
|
515
|
+
return (await one(q.order('created_at', { ascending: false }).limit(limit))).map(rowFrom).reverse()
|
|
516
|
+
},
|
|
517
|
+
async countWorkspaceMessages (workspaceId, { after = 0, notBy = '' } = {}) {
|
|
518
|
+
const { count, error } = await db.from('workspace_messages').select('id', { count: 'exact', head: true }).eq('workspace_id', workspaceId).gt('created_at', ts(after)).neq('account', notBy)
|
|
519
|
+
if (error) throw error
|
|
520
|
+
return count || 0
|
|
521
|
+
},
|
|
522
|
+
async workspaceReadAt (workspaceId, account) {
|
|
523
|
+
const row = await one(db.from('workspace_message_reads').select('read_at').eq('workspace_id', workspaceId).eq('account', account).maybeSingle())
|
|
524
|
+
return row ? ms(row.read_at) : 0
|
|
525
|
+
},
|
|
526
|
+
async setWorkspaceReadAt (workspaceId, account, at) {
|
|
527
|
+
await one(db.from('workspace_message_reads').upsert({ workspace_id: workspaceId, account, read_at: ts(at) }, { onConflict: 'workspace_id,account' }))
|
|
528
|
+
},
|
|
529
|
+
|
|
506
530
|
async listWorkspaceInvites (workspaceId) {
|
|
507
531
|
return (await one(db.from('workspace_invites').select(WORKSPACE_INVITE).eq('workspace_id', workspaceId).order('created_at', { ascending: false }).limit(50))).map(rowFrom)
|
|
508
532
|
},
|
package/src/app-tools.js
CHANGED
|
@@ -38,13 +38,13 @@ export const APP_INPUTS = {
|
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
const LEVEL = { session: 'this codebase', workspace: 'the project', org: 'the team' }
|
|
41
|
+
const LEVEL = { session: 'this codebase', workspace: 'the project', org: 'the team', account: 'every project of its owner' }
|
|
42
42
|
|
|
43
43
|
/** quilt_apps' answer. */
|
|
44
44
|
export function describeApps (b) {
|
|
45
45
|
if (!b.apps || !b.apps.length) return 'No apps are connected for this codebase yet. A person connects one in Codebase settings → Connections (or for the whole project or team), and then you can use it here.'
|
|
46
46
|
const lines = ['Apps you can use here (quilt_app_tools finds an action, quilt_app_call runs it):']
|
|
47
|
-
for (const a of b.apps) lines.push(`- ${a.name} (app: "${a.app}", connection: "${a.id}") — connected for ${LEVEL[a.level] || a.level}${a.levelName ? ` (${a.levelName})` : ''} by ${a.by}${a.who === 'people' ? '; people and their own AIs only' : ''}`)
|
|
47
|
+
for (const a of b.apps) lines.push(`- ${a.name} (app: "${a.app}", connection: "${a.id}") — connected for ${LEVEL[a.level] || a.level}${a.levelName ? ` (${a.levelName})` : ''} by ${a.by}${a.who === 'people' ? '; people and their own AIs only' : a.who === 'agents' ? '; for the agents chosen for it only' : ''}`)
|
|
48
48
|
lines.push('', `Actions that only read run at once; anything else waits for a person to approve it in the codebase's chat. At most ${b.callsPerDay} app calls a day.`)
|
|
49
49
|
return lines.join('\n')
|
|
50
50
|
}
|
package/src/ui/app.css
CHANGED
|
@@ -1694,7 +1694,9 @@ body.has-asks .prail { margin-top: calc(var(--update-bar, 0px) + var(--asks-bar)
|
|
|
1694
1694
|
.pj-app .toggle { grid-area: 1 / 2; align-self: start; }
|
|
1695
1695
|
.pj-app b { grid-area: 3 / 1 / 4 / 3; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1696
1696
|
.pj-app .hint { grid-area: 4 / 1 / 5 / 3; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1697
|
-
.pj-app .
|
|
1697
|
+
.pj-app .pj-pills { grid-area: 5 / 1 / 6 / 3; display: flex; flex-wrap: wrap; gap: 4px; margin-top: 8px; min-width: 0; }
|
|
1698
|
+
.pj-app .pj-pills:empty { display: none; }
|
|
1699
|
+
.pj-app .pj-pills .pill { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1698
1700
|
.pj-slot { display: flex; align-items: center; justify-content: center; gap: 8px; border: 1.5px dashed var(--border-strong); background: none; color: var(--muted); font: 500 13px var(--sans); cursor: pointer; }
|
|
1699
1701
|
.pj-slot:hover { color: var(--text); border-color: var(--muted); }
|
|
1700
1702
|
.pj-slot svg { width: 15px; height: 15px; }
|
|
@@ -1827,6 +1829,15 @@ body.has-asks .prail { margin-top: calc(var(--update-bar, 0px) + var(--asks-bar)
|
|
|
1827
1829
|
.pj-preview .hint { margin: 8px 0 0; }
|
|
1828
1830
|
@media (max-width: 760px) { .pj-add-row { flex-direction: column; } .pj-preview { grid-template-columns: minmax(0, 1fr); } }
|
|
1829
1831
|
|
|
1832
|
+
/* A project's channel: the chat a codebase has, across the page. */
|
|
1833
|
+
.pj-pmain.pj-chat { display: flex; flex-direction: column; overflow: hidden; padding: 0; }
|
|
1834
|
+
.pj-chanpage, .pj-chan { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
|
1835
|
+
.pj-chan .files-head { flex: none; margin: 0; padding: 16px 24px 12px; border-bottom: 1px solid var(--border); }
|
|
1836
|
+
.pj-chan .files-head .pj-hash { margin-right: 6px; color: var(--muted); }
|
|
1837
|
+
.pj-chan .messages { padding: 18px 24px; }
|
|
1838
|
+
.pj-chan .composer { flex: none; padding: 12px 24px 20px; }
|
|
1839
|
+
.pj-rooms button .avatar { width: 18px; height: 18px; font-size: 9px; flex: none; }
|
|
1840
|
+
|
|
1830
1841
|
/* A project's task board: the board a codebase has, with a row of chips to narrow it to one codebase and each card wearing its codebase. */
|
|
1831
1842
|
.pj-pmain.pj-tasks { display: flex; flex-direction: column; overflow: hidden; padding-bottom: 24px; }
|
|
1832
1843
|
.pj-board { flex: 1; min-height: 0; display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--border-strong); border-radius: 8px; overflow: hidden; }
|
|
@@ -3037,6 +3048,9 @@ label.radio:has(input:disabled) { cursor: default; opacity: .75; }
|
|
|
3037
3048
|
.cn-state { font-size: 11.5px; font-weight: 600; color: var(--warn); white-space: nowrap; } .cn-state.failed { color: var(--bad); }
|
|
3038
3049
|
.cn-foot { display: flex; align-items: center; gap: 8px; } .cn-foot .spacer { flex: 1; }
|
|
3039
3050
|
.cn-confirm { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; }
|
|
3051
|
+
.cn-agents { display: flex; flex-wrap: wrap; gap: 6px 14px; padding-top: 10px; border-top: 1px solid var(--border); }
|
|
3052
|
+
.cn-agent { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
|
|
3053
|
+
.cn-agents .hint { flex-basis: 100%; }
|
|
3040
3054
|
.cn-apps { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px; }
|
|
3041
3055
|
.cn-app { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); min-width: 0; }
|
|
3042
3056
|
.cn-app b { flex: 1; min-width: 0; font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
package/src/ui/connections.js
CHANGED
|
@@ -2,13 +2,28 @@
|
|
|
2
2
|
// button): apps people connect for a session, workspace or team through Composio, which keeps the
|
|
3
3
|
// sign-ins (plans/app-connections.md). Agents use them with quilt_apps / quilt_app_tools /
|
|
4
4
|
// quilt_app_call. Also the approval card an app action waiting for a person draws in the chat.
|
|
5
|
+
// A person's own connections ({ type: 'account', id: 'me' }) are for every project of theirs. A
|
|
6
|
+
// connection is for people and agents, for people only, or for the agents chosen for it.
|
|
5
7
|
import { api, esc, toast, ago, I } from './common.js'
|
|
6
8
|
|
|
7
9
|
const SEARCH_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>'
|
|
8
10
|
|
|
9
11
|
const views = new Map() // `${type}:${id}` -> the last view, so a redraw shows it at once
|
|
10
12
|
const urlOf = (type, id, rest = '') => `/api/connections/${type}/${encodeURIComponent(id)}${rest}`
|
|
11
|
-
const LEVEL = { session: 'this codebase', workspace: 'the project', org: 'the team' }
|
|
13
|
+
const LEVEL = { session: 'this codebase', workspace: 'the project', org: 'the team', account: 'every project of yours' }
|
|
14
|
+
const FROM = { ...LEVEL, account: 'every project' }
|
|
15
|
+
|
|
16
|
+
// Your agents, asked once: who a connection can be for. A page that knows more (a project's agents) hands them in.
|
|
17
|
+
let mine = null
|
|
18
|
+
const yourAgents = () => (mine ||= api('GET', '/api/agents').then((r) => (r.agents || []).map((a) => ({ id: a.id, name: a.name })), () => []))
|
|
19
|
+
|
|
20
|
+
/** Who a connection is for, in a few words. `names`: agent id -> name. */
|
|
21
|
+
export function whoWords (c, names = new Map()) {
|
|
22
|
+
if (c.who === 'people') return 'People only'
|
|
23
|
+
if (c.who !== 'agents') return 'People and agents'
|
|
24
|
+
const list = (c.agents || []).map((id) => names.get(id) || 'an agent')
|
|
25
|
+
return `Only ${list.length > 3 ? `${list.slice(0, 3).join(', ')} and ${list.length - 3} more` : list.join(', ')}`
|
|
26
|
+
}
|
|
12
27
|
const STATUS = { active: 'Connected', pending: 'Waiting for sign-in', failed: 'Didn\'t connect' }
|
|
13
28
|
const SHOWN = 12
|
|
14
29
|
|
|
@@ -18,10 +33,13 @@ const logoHtml = (a) => a.logo
|
|
|
18
33
|
|
|
19
34
|
/**
|
|
20
35
|
* Draws the card into `root` for one scope ({ type, id }: a session's room, a workspace's id, a
|
|
21
|
-
* team's slug).
|
|
36
|
+
* team's slug, or 'account' with 'me'). `agents()`: more agents a connection here can be for
|
|
37
|
+
* ([{ id, name }]: a project's), besides your own. Answers { refresh, destroy }.
|
|
22
38
|
*/
|
|
23
|
-
export function mountConnections (root, { type, id }) {
|
|
24
|
-
const ui = { search: '', apps: null, appsFor: null, more: false, busy: '', error: '', calls: null, confirm: null }
|
|
39
|
+
export function mountConnections (root, { type, id, agents = () => [] }) {
|
|
40
|
+
const ui = { search: '', apps: null, appsFor: null, more: false, busy: '', error: '', calls: null, confirm: null, choosing: null, yours: [] }
|
|
41
|
+
/** The agents a connection here can be for, once each. */
|
|
42
|
+
const choices = () => { const seen = new Map(); for (const a of [...agents(), ...ui.yours]) if (a && a.id && !seen.has(a.id)) seen.set(a.id, a.name || 'an agent'); return seen }
|
|
25
43
|
let view = views.get(`${type}:${id}`) || null
|
|
26
44
|
let alive = true
|
|
27
45
|
let poll = null
|
|
@@ -29,17 +47,26 @@ export function mountConnections (root, { type, id }) {
|
|
|
29
47
|
|
|
30
48
|
function connectedHtml (c, own) {
|
|
31
49
|
const status = c.status === 'active' ? '' : `<span class="cn-state ${esc(c.status)}">${esc(STATUS[c.status] || c.status)}</span>`
|
|
50
|
+
const names = choices()
|
|
51
|
+
// Chosen agents: the ones it is for are ticked; a tick saves at once, and at least one stays ticked.
|
|
52
|
+
const picking = own && c.mayChange && c.status === 'active' && (c.who === 'agents' || ui.choosing === c.id)
|
|
53
|
+
const value = picking ? 'agents' : c.who
|
|
32
54
|
const who = own && c.mayChange && c.status === 'active'
|
|
33
|
-
? `<select class="input sm" data-who="${esc(c.id)}" aria-label="Who may use ${esc(c.name)}"><option value="all"${
|
|
34
|
-
: `<span class="hint">${c
|
|
55
|
+
? `<select class="input sm" data-who="${esc(c.id)}" aria-label="Who may use ${esc(c.name)}"><option value="all"${value === 'all' ? ' selected' : ''}>People and agents</option><option value="agents"${value === 'agents' ? ' selected' : ''}>People and chosen agents</option><option value="people"${value === 'people' ? ' selected' : ''}>People only</option></select>`
|
|
56
|
+
: `<span class="hint">${esc(whoWords(c, names))}</span>`
|
|
57
|
+
const chosen = new Set(c.who === 'agents' ? c.agents || [] : [])
|
|
58
|
+
for (const a of chosen) if (!names.has(a)) names.set(a, 'an agent')
|
|
59
|
+
const pick = !picking ? '' : `<div class="cn-agents" role="group" aria-label="The agents that may use ${esc(c.name)}">${names.size
|
|
60
|
+
? [...names].map(([aid, name]) => `<label class="cn-agent"><input type="checkbox" data-agent-of="${esc(c.id)}" value="${esc(aid)}"${chosen.has(aid) ? ' checked' : ''}><span>${esc(name)}</span></label>`).join('')
|
|
61
|
+
: '<span class="hint">You have no agents yet.</span>'}${chosen.size ? '' : '<span class="hint">Tick the agents that may use it. Until then it stays as it was.</span>'}</div>`
|
|
35
62
|
const remove = own && c.mayChange
|
|
36
63
|
? (ui.confirm === c.id
|
|
37
64
|
? `<span class="cn-confirm">Remove ${esc(c.name)}? <button class="btn sm danger" data-remove="${esc(c.id)}">Remove</button><button class="btn sm ghost" data-cancel>Keep</button></span>`
|
|
38
65
|
: `<button class="btn sm ghost icon" data-ask-remove="${esc(c.id)}" title="Remove ${esc(c.name)}" aria-label="Remove ${esc(c.name)}">${I.trash}</button>`)
|
|
39
66
|
: ''
|
|
40
67
|
return `<div class="cn-card${c.status === 'active' ? '' : ' off'}">
|
|
41
|
-
<div class="cn-top">${logoHtml(c)}<div class="cn-what"><b>${esc(c.name)}</b><small>${own ? `${c.status === 'active' ? 'Connected' : 'Started'} by ${esc(c.by)} · ${esc(ago(c.createdAt))}` : `From ${esc(
|
|
42
|
-
<div class="cn-foot">${who}<span class="spacer"></span>${remove}</div
|
|
68
|
+
<div class="cn-top">${logoHtml(c)}<div class="cn-what"><b>${esc(c.name)}</b><small>${own ? `${c.status === 'active' ? 'Connected' : 'Started'} by ${esc(c.by)} · ${esc(ago(c.createdAt))}` : `From ${esc(FROM[c.level] || c.level)}${c.levelName ? ` (${esc(c.levelName)})` : ''} · by ${esc(c.by)}`}</small></div>${status}</div>
|
|
69
|
+
<div class="cn-foot">${who}<span class="spacer"></span>${remove}</div>${pick}</div>`
|
|
43
70
|
}
|
|
44
71
|
|
|
45
72
|
function appHtml (a, connected) {
|
|
@@ -76,6 +103,8 @@ export function mountConnections (root, { type, id }) {
|
|
|
76
103
|
if (had) { const s = root.querySelector('[data-search]'); s.focus(); s.setSelectionRange(s.value.length, s.value.length) }
|
|
77
104
|
}
|
|
78
105
|
|
|
106
|
+
yourAgents().then((list) => { ui.yours = list; if (alive && view) draw() })
|
|
107
|
+
|
|
79
108
|
async function load () {
|
|
80
109
|
try {
|
|
81
110
|
view = await api('GET', urlOf(type, id))
|
|
@@ -110,8 +139,19 @@ export function mountConnections (root, { type, id }) {
|
|
|
110
139
|
})
|
|
111
140
|
|
|
112
141
|
root.addEventListener('change', async (e) => {
|
|
142
|
+
const box = e.target.closest('[data-agent-of]')
|
|
143
|
+
if (box) {
|
|
144
|
+
const cid = box.dataset.agentOf
|
|
145
|
+
const ids = [...root.querySelectorAll(`[data-agent-of="${cid}"]:checked`)].map((b) => b.value)
|
|
146
|
+
if (!ids.length) { box.checked = true; return toast('At least one agent: or pick People only.') }
|
|
147
|
+
try { await api('PATCH', urlOf(type, id, `/${cid}`), { who: 'agents', agents: ids }); ui.choosing = null; load() } catch (err) { toast(err.message); load() }
|
|
148
|
+
return
|
|
149
|
+
}
|
|
113
150
|
const sel = e.target.closest('[data-who]')
|
|
114
151
|
if (!sel) return
|
|
152
|
+
// Chosen agents is saved with the first agent ticked, never as an empty list.
|
|
153
|
+
if (sel.value === 'agents') { ui.choosing = sel.dataset.who; return draw() }
|
|
154
|
+
ui.choosing = null
|
|
115
155
|
try { await api('PATCH', urlOf(type, id, `/${sel.dataset.who}`), { who: sel.value }); load() } catch (err) { toast(err.message); load() }
|
|
116
156
|
})
|
|
117
157
|
|
package/src/ui/home.js
CHANGED
|
@@ -20,6 +20,7 @@ import { feedbackDockHtml, bindFeedback } from './feedback.js'
|
|
|
20
20
|
import { openNewCodebase } from './new-session.js'
|
|
21
21
|
import { projectShellHtml, bindProjectShell } from './projects.js'
|
|
22
22
|
import { holdProjectBoard } from './project-board.js'
|
|
23
|
+
import { mountConnections } from './connections.js'
|
|
23
24
|
import { openProjectPop } from './project-pop.js'
|
|
24
25
|
|
|
25
26
|
export const tildify = (p) => state.defaults.home && String(p).startsWith(state.defaults.home) ? `~${String(p).slice(state.defaults.home.length)}` : p
|
|
@@ -657,10 +658,11 @@ const SETTINGS_TABS = [['agents', 'Agents', 'bot'], ['git', 'Version control', '
|
|
|
657
658
|
// starts with. Your own AI then has a part to itself (Your AI), apart from the agents every project gets.
|
|
658
659
|
const PROJECT_SETTINGS = [
|
|
659
660
|
{ label: 'You', tabs: [['ai', 'Your AI', 'bot'], ['you', 'Profile', 'user'], ['account', 'Account', 'gear']] },
|
|
660
|
-
{ label: 'Every project', tabs: [['agents', 'Agents', 'bot'], ['git', 'Version control', 'branch'], ['workspaces', 'Projects', 'grid']] },
|
|
661
|
+
{ label: 'Every project', tabs: [['agents', 'Agents', 'bot'], ['connections', 'Connections', 'link'], ['git', 'Version control', 'branch'], ['workspaces', 'Projects', 'grid']] },
|
|
661
662
|
{ label: 'New codebases', tabs: [['session', 'Defaults', 'folder']] }
|
|
662
663
|
]
|
|
663
|
-
|
|
664
|
+
// Connections for every project show only while the accounts API has connections on.
|
|
665
|
+
const settingsGroups = () => state.workspacesOn ? PROJECT_SETTINGS.map((g) => ({ ...g, tabs: g.tabs.filter(([id]) => id !== 'connections' || state.connectionsOn) })) : [{ label: '', tabs: SETTINGS_TABS.filter(([id]) => id !== 'workspaces') }]
|
|
664
666
|
const settingsTabs = () => settingsGroups().flatMap((g) => g.tabs)
|
|
665
667
|
/** The tab your own AI (the tool on this computer, your cloud AI) is on. */
|
|
666
668
|
const aiTab = () => state.workspacesOn ? 'ai' : 'agents'
|
|
@@ -714,9 +716,10 @@ function settingsHtml (session = null) {
|
|
|
714
716
|
const a = state.account || { name: p.name, email: '' }
|
|
715
717
|
const theme = p.theme || document.documentElement.dataset.theme || 'dark'
|
|
716
718
|
const tab = settingsTab()
|
|
717
|
-
const show = (id) => ({ account: ['account', 'about', 'computer'], you: ['profile', 'appearance', 'sounds'], session: ['sessions'], ai: ['your-ai', 'cloud-ai'], agents: state.workspacesOn ? ['agents'] : ['your-ai', 'cloud-ai', 'agents'], git: ['agents-git'], workspaces: ['workspaces'] })[tab].includes(id)
|
|
719
|
+
const show = (id) => ({ account: ['account', 'about', 'computer'], you: ['profile', 'appearance', 'sounds'], session: ['sessions'], ai: ['your-ai', 'cloud-ai'], agents: state.workspacesOn ? ['agents'] : ['your-ai', 'cloud-ai', 'agents'], git: ['agents-git'], workspaces: ['workspaces'], connections: [] })[tab].includes(id)
|
|
718
720
|
return `
|
|
719
721
|
${tab === 'workspaces' ? workspacesSettingsHtml() : ''}
|
|
722
|
+
${tab === 'connections' ? '<section class="card settings-sec" id="account-connections-sec"><div class="sec-intro"><h2>Connections for every project</h2><p>Apps the agents in every project of yours can use. Agents never see the logins.</p></div><div class="sec-body"><div data-account-connections></div></div></section>' : ''}
|
|
720
723
|
${show('account') ? `<section class="card settings-sec" id="account-sec">
|
|
721
724
|
<div class="sec-intro"><h2>Account</h2><p>This computer is signed in to your heyquilt.com account.</p></div>
|
|
722
725
|
<div class="sec-body">
|
|
@@ -936,6 +939,8 @@ function bindAgents (root) {
|
|
|
936
939
|
|
|
937
940
|
/** Wires the settings cards inside `root`; `refresh()` redraws them after a save. */
|
|
938
941
|
function bindSettings (root, refresh) {
|
|
942
|
+
const own = root.querySelector('[data-account-connections]')
|
|
943
|
+
if (own) mountConnections(own, { type: 'account', id: 'me' })
|
|
939
944
|
// Projects: Open goes to the project's page (the pop-up closes; the old shell's sidebar binds its own).
|
|
940
945
|
if (state.workspacesOn) root.querySelectorAll('#workspaces-sec [data-view]').forEach((b) => { b.onclick = () => { $('#settings-back')?.remove(); go(b.dataset.view) } })
|
|
941
946
|
// Tabs: the pick is kept on this computer, and the cards are drawn again.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// A project's channel (projects on): one conversation for everyone in the project, there with no
|
|
2
|
+
// codebase open. The accounts API keeps it (routes/workspace-chat.js); the app asks for what is
|
|
3
|
+
// new every few seconds while a project's page is open. A codebase's own channel is its chat.
|
|
4
|
+
import { I, state, $, esc, api, toast, avatar, clock } from './common.js'
|
|
5
|
+
import { textHtml } from './chat.js'
|
|
6
|
+
|
|
7
|
+
const ASK_MS = 4000
|
|
8
|
+
const chans = new Map() // project id -> { messages, unread, asked, loaded, failed }
|
|
9
|
+
const chan = (id) => { if (!chans.has(id)) chans.set(id, { messages: [], unread: 0, asked: 0, loaded: false, failed: '', draft: '' }); return chans.get(id) }
|
|
10
|
+
let live = null // the channel on the page: { el, id }
|
|
11
|
+
|
|
12
|
+
/** How many messages are new for you in a project's channel, as last heard. */
|
|
13
|
+
export const channelUnread = (id) => chan(id).unread
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Asks for what is new in a project's channel (at most every few seconds; `now` asks at once).
|
|
17
|
+
* `changed()` is called when the count of what is new changes; the open channel draws itself.
|
|
18
|
+
*/
|
|
19
|
+
export async function loadChannel (id, changed = () => {}, { now = false } = {}) {
|
|
20
|
+
const c = chan(id)
|
|
21
|
+
if (!now && Date.now() - c.asked < ASK_MS) return
|
|
22
|
+
c.asked = Date.now()
|
|
23
|
+
try {
|
|
24
|
+
const after = c.messages.length ? c.messages[c.messages.length - 1].at : 0
|
|
25
|
+
const r = await api('GET', `/api/workspaces/${encodeURIComponent(id)}/messages${after ? `?after=${after}` : ''}`)
|
|
26
|
+
const had = c.messages.length; const was = c.unread
|
|
27
|
+
const known = new Set(c.messages.map((m) => m.id))
|
|
28
|
+
for (const m of r.messages) if (!known.has(m.id)) c.messages.push(m)
|
|
29
|
+
c.loaded = true; c.failed = ''
|
|
30
|
+
c.unread = r.unread
|
|
31
|
+
const open = live && live.id === id && live.el.isConnected
|
|
32
|
+
if (open && (c.messages.length !== had || !live.drawn)) live.draw()
|
|
33
|
+
// Reading it on the page is reading it: what came in while it is open is not new.
|
|
34
|
+
if (open && c.unread && document.hasFocus()) { c.unread = 0; api('POST', `/api/workspaces/${encodeURIComponent(id)}/messages/read`).catch(() => {}) }
|
|
35
|
+
if (c.unread !== was) changed()
|
|
36
|
+
} catch (err) {
|
|
37
|
+
c.failed = err.message
|
|
38
|
+
if (!c.loaded && live && live.id === id && live.el.isConnected) live.draw()
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Draws a project's channel into `el` and keeps it working. `changed()`: the count of what is new changed (the sidebar shows it). */
|
|
43
|
+
export function mountChannel (el, { d, changed = () => {} }) {
|
|
44
|
+
const id = d.workspace.id
|
|
45
|
+
const c = chan(id)
|
|
46
|
+
const me = state.profile?.name || ''
|
|
47
|
+
const names = () => [...new Set([d.owner?.name, ...(d.members || []).map((m) => m.name), ...(d.agents || []).map((a) => a.name)].filter(Boolean))]
|
|
48
|
+
el.innerHTML = `
|
|
49
|
+
<div class="pj-chan">
|
|
50
|
+
<div class="files-head"><div class="t"><h2 class="crumbs"><span class="pj-hash">#</span>${esc(d.workspace.name)}</h2><p class="hint">Everyone in ${esc(d.workspace.name)} and its agents. It is here with no codebase open.</p></div></div>
|
|
51
|
+
<div class="messages" data-chan-list aria-live="polite"></div>
|
|
52
|
+
<form class="composer" data-chan-form><div class="box"><textarea rows="1" maxlength="8000" placeholder="Message ${esc(d.workspace.name)}…" aria-label="Message ${esc(d.workspace.name)}"></textarea><button type="submit" class="btn primary icon" title="Send" aria-label="Send">${I.send}</button></div></form>
|
|
53
|
+
</div>`
|
|
54
|
+
const list = $('[data-chan-list]', el)
|
|
55
|
+
const box = $('textarea', el)
|
|
56
|
+
const draw = () => {
|
|
57
|
+
const near = list.scrollHeight - list.scrollTop - list.clientHeight < 80
|
|
58
|
+
const all = names()
|
|
59
|
+
list.innerHTML = c.messages.length
|
|
60
|
+
? c.messages.map((m) => `<div class="msg${m.mine ? ' mine' : ''}"><div style="min-width:0"><div class="head">${m.mine ? '' : avatar(m.by)}<b>${m.mine ? 'You' : esc(m.by)}</b>${m.kind === 'agent' ? `<span class="tag bot">${I.bot}agent</span>` : ''}<span>${esc(clock(m.at))}</span></div><div class="bubble"><div class="text">${textHtml(m.text, all, me)}</div></div></div></div>`).join('')
|
|
61
|
+
: `<div class="day-empty"><div><b>${c.failed ? 'The channel could not be read.' : c.loaded ? 'Say hi.' : 'Loading…'}</b></div><div class="hint">${c.failed ? esc(c.failed) : c.loaded ? `What is written here reaches everyone in ${esc(d.workspace.name)}, whichever codebase they are in.` : ''}</div></div>`
|
|
62
|
+
if (near || !live.drawn) list.scrollTop = list.scrollHeight
|
|
63
|
+
live.drawn = true
|
|
64
|
+
}
|
|
65
|
+
live = { el, id, draw, drawn: false }
|
|
66
|
+
draw()
|
|
67
|
+
const grow = () => { box.style.height = 'auto'; box.style.height = `${Math.min(box.scrollHeight, 160)}px` }
|
|
68
|
+
// The page is drawn again when a codebase's state changes: what was being typed is put back.
|
|
69
|
+
box.value = c.draft
|
|
70
|
+
box.oninput = () => { c.draft = box.value; grow() }
|
|
71
|
+
grow()
|
|
72
|
+
box.onkeydown = (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('[data-chan-form]', el).requestSubmit() } }
|
|
73
|
+
$('[data-chan-form]', el).onsubmit = async (e) => {
|
|
74
|
+
e.preventDefault()
|
|
75
|
+
const text = box.value.trim()
|
|
76
|
+
if (!text) return
|
|
77
|
+
box.value = ''; c.draft = ''; grow()
|
|
78
|
+
try {
|
|
79
|
+
const r = await api('POST', `/api/workspaces/${encodeURIComponent(id)}/messages`, { text })
|
|
80
|
+
if (!c.messages.some((m) => m.id === r.message.id)) c.messages.push(r.message)
|
|
81
|
+
draw(); list.scrollTop = list.scrollHeight
|
|
82
|
+
} catch (err) { toast(err.message); if (!box.value) { box.value = text; c.draft = text; grow() } }
|
|
83
|
+
box.focus()
|
|
84
|
+
}
|
|
85
|
+
// Opening it is reading it.
|
|
86
|
+
const read = () => { if (!c.unread) return; c.unread = 0; changed(); api('POST', `/api/workspaces/${encodeURIComponent(id)}/messages/read`).catch(() => {}) }
|
|
87
|
+
loadChannel(id, changed, { now: true }).then(read)
|
|
88
|
+
// Coming back to the window with the channel open is reading it.
|
|
89
|
+
const onFocus = () => { if (!el.isConnected) return window.removeEventListener('focus', onFocus); read() }
|
|
90
|
+
window.addEventListener('focus', onFocus)
|
|
91
|
+
// The cursor goes to the box, unless a pop-up is open over the page.
|
|
92
|
+
if (!document.querySelector('.modal-back')) { box.focus(); box.setSelectionRange(box.value.length, box.value.length) }
|
|
93
|
+
}
|
package/src/ui/project-model.js
CHANGED
|
@@ -195,3 +195,30 @@ export function projectPeople (d, me = '') {
|
|
|
195
195
|
return [...owner, ...(d.members || []).filter((m) => m && !isAgent(m) && !owner.some((o) => o.account === m.account)).map((m) => ({ account: m.account, name: m.name || m.account, access: m.access || 'edit', owner: false }))]
|
|
196
196
|
.map((m) => ({ ...m, you: !!me && m.account === me }))
|
|
197
197
|
}
|
|
198
|
+
|
|
199
|
+
// -------------------------------------------------------------- channels --
|
|
200
|
+
/**
|
|
201
|
+
* The people and agents you have direct messages with in a codebase, the latest first:
|
|
202
|
+
* [{ name, ts }]. `messages`: the codebase's chat ({ by, to, ts }); `me`: your name there.
|
|
203
|
+
*/
|
|
204
|
+
export function dmThreads (messages = [], me = '') {
|
|
205
|
+
const last = new Map()
|
|
206
|
+
for (const m of messages) {
|
|
207
|
+
if (!m || !m.to || !m.by) continue
|
|
208
|
+
const other = m.by === me ? m.to : m.to === me ? m.by : ''
|
|
209
|
+
if (!other || other === me) continue
|
|
210
|
+
if ((m.ts || 0) >= (last.get(other) ?? -1)) last.set(other, m.ts || 0)
|
|
211
|
+
}
|
|
212
|
+
return [...last].map(([name, ts]) => ({ name, ts })).sort((a, b) => b.ts - a.ts)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A project's direct messages, across its codebases open here: one row a person, the codebase
|
|
217
|
+
* where you last wrote to each other. `codes`: [{ id, name, messages, me }]. Answers
|
|
218
|
+
* [{ name, ts, code, codeName }], the latest first.
|
|
219
|
+
*/
|
|
220
|
+
export function projectDms (codes = []) {
|
|
221
|
+
const best = new Map()
|
|
222
|
+
for (const c of codes) for (const t of dmThreads(c.messages, c.me)) { const b = best.get(t.name); if (!b || t.ts > b.ts) best.set(t.name, { ...t, code: c.id, codeName: c.name }) }
|
|
223
|
+
return [...best.values()].sort((a, b) => b.ts - a.ts)
|
|
224
|
+
}
|
package/src/ui/project-pop.js
CHANGED
|
@@ -444,7 +444,7 @@ export function openProjectPop ({ id, section = 'general', focusInvite = false }
|
|
|
444
444
|
if (more) more.onclick = () => { addingAgent = true; pop.redraw() }
|
|
445
445
|
const fresh = $('[data-agent-new]', el)
|
|
446
446
|
if (fresh) fresh.onclick = () => { state.settingsTab = 'agents'; openSettings() }
|
|
447
|
-
} else if (s === 'connections') mountConnections($('[data-pop-connections]', el), { type: 'workspace', id })
|
|
447
|
+
} else if (s === 'connections') mountConnections($('[data-pop-connections]', el), { type: 'workspace', id, agents: () => (d().agents || []).filter((x) => x.agentId).map((x) => ({ id: x.agentId, name: x.name })) })
|
|
448
448
|
}
|
|
449
449
|
})
|
|
450
450
|
return pop
|
package/src/ui/projects.js
CHANGED
|
@@ -4,13 +4,14 @@
|
|
|
4
4
|
// (prail.js) moves between projects. home.js draws this in place of its own sidebar and pages.
|
|
5
5
|
import { I, state, $, esc, ago, api, toast, ask, avatar, COLORS, loadingHtml } from './common.js'
|
|
6
6
|
import { quiltMark } from './mark.js'
|
|
7
|
-
import { quiltBlock, projectCodebases, looseCodebases, whoLine, readFolded } from './project-model.js'
|
|
7
|
+
import { quiltBlock, projectCodebases, looseCodebases, whoLine, readFolded, projectDms } from './project-model.js'
|
|
8
|
+
import { mountChannel, loadChannel, channelUnread } from './project-channel.js'
|
|
8
9
|
import { tileLetter } from './prail-model.js'
|
|
9
10
|
import { loadWorkspaces, openWorkspace, wsIdOf } from './workspaces.js'
|
|
10
11
|
import { openNewProject, openProjectPop } from './project-pop.js'
|
|
11
12
|
import { artifactsHtml, bindAllFiles } from './files.js'
|
|
12
13
|
import { mountProjectBoard, projectOpenTasks } from './project-board.js'
|
|
13
|
-
import { mountConnections } from './connections.js'
|
|
14
|
+
import { mountConnections, whoWords } from './connections.js'
|
|
14
15
|
import { toolLogo } from './tool-logo.js'
|
|
15
16
|
import { FOREIGN_JOINS } from './agent-place.js'
|
|
16
17
|
|
|
@@ -33,7 +34,7 @@ export function toggleFolded (k) { const f = foldedNow(); f.has(k) ? f.delete(k)
|
|
|
33
34
|
/** The project a view shows, as the list of projects has it; null on Home. */
|
|
34
35
|
const projectOfView = (view) => /^(ws|wsfiles):/.test(view) ? (state.workspaces || []).find((w) => w.id === wsIdOf(view)) || { id: wsIdOf(view), name: '', color: '' } : null
|
|
35
36
|
/** The page of a project that is showing: its overview, its tasks, its artifacts or its connections. */
|
|
36
|
-
const pageOf = (view) => view.startsWith('wsfiles:') ? 'artifacts' : state.projectPage === 'tasks' ? 'tasks' : state.projectPage === 'connections' && state.connectionsOn ? 'connections' : ''
|
|
37
|
+
const pageOf = (view) => view.startsWith('wsfiles:') ? 'artifacts' : state.projectPage === 'tasks' ? 'tasks' : state.projectPage === 'channel' ? 'channel' : state.projectPage === 'connections' && state.connectionsOn ? 'connections' : ''
|
|
37
38
|
|
|
38
39
|
// ---------------------------------------------------------------- header --
|
|
39
40
|
function headerHtml (p) {
|
|
@@ -141,19 +142,34 @@ function projectAgentsHtml (d) {
|
|
|
141
142
|
const appFace = (c) => `<span class="pj-face md sq">${c.logo ? `<img src="${esc(c.logo)}" alt="" loading="lazy" referrerpolicy="no-referrer">` : `<i class="show">${esc(String(c.name || '?').slice(0, 1).toUpperCase())}</i>`}</span>`
|
|
142
143
|
const APP_STATE = { pending: 'Waiting for sign-in', failed: "Didn't connect" }
|
|
143
144
|
|
|
144
|
-
/**
|
|
145
|
-
function
|
|
145
|
+
/** Agent id -> name, from what the pages know: your agents and the open project's. */
|
|
146
|
+
function agentNames () {
|
|
147
|
+
const names = new Map((state.placedAgents || []).map((a) => [a.id, a.name]))
|
|
148
|
+
for (const a of (state.workspace && state.workspace.agents) || []) if (a.agentId) names.set(a.agentId, a.name)
|
|
149
|
+
return names
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Connections as tiles: a project's (its own and the ones it gets from above), or on Home your
|
|
154
|
+
* own, which every project of yours gets. `v`: what the accounts API says (null: not asked yet).
|
|
155
|
+
* The switch says whether agents may use it; one for chosen agents wears who they are.
|
|
156
|
+
*/
|
|
157
|
+
function appsSectionHtml (v, { home = false } = {}) {
|
|
146
158
|
const own = v ? v.connections || [] : []
|
|
147
159
|
const above = v ? v.inherited || [] : []
|
|
160
|
+
const names = agentNames()
|
|
161
|
+
const from = (c, mine) => home ? '' : mine ? scopePill(true) : c.level === 'org' ? `<span class="pill pj-scope" title="Connected for the team">${esc(c.levelName || 'Team')}</span>` : scopePill(false)
|
|
162
|
+
const only = (c) => c.who === 'agents' ? `<span class="pill pj-scope own" title="Agents that were not chosen can't use it">${esc(whoWords(c, names))}</span>` : ''
|
|
148
163
|
const tile = (c, mine) => `
|
|
149
|
-
<div class="pj-app pj-item">${appFace(c)}${sw(`data-app-who="${esc(c.id)}" aria-label="${esc(c.name)}: agents may use it"`, c.who !== 'people' && c.status === 'active', { disabled: !mine || !c.mayChange || c.status !== 'active', why: mine ? '' : `Set where it was connected${c.levelName ? ` (${c.levelName})` : ''}` })}<b>${esc(c.name)}</b><span class="hint" title="Connected by ${esc(c.by)}">${esc(APP_STATE[c.status] || `Connected by ${c.by}`)}</span>${
|
|
164
|
+
<div class="pj-app pj-item">${appFace(c)}${sw(`data-app-who="${esc(c.id)}" aria-label="${esc(c.name)}: agents may use it"`, c.who !== 'people' && c.status === 'active', { disabled: !mine || !c.mayChange || c.status !== 'active', why: mine ? '' : `Set where it was connected${c.level === 'account' ? ' (Home)' : c.levelName ? ` (${c.levelName})` : ''}` })}<b>${esc(c.name)}</b><span class="hint" title="Connected by ${esc(c.by)}">${esc(APP_STATE[c.status] || `Connected by ${c.by}`)}</span><span class="pj-pills">${from(c, mine)}${only(c)}</span></div>`
|
|
150
165
|
const n = own.length + above.length
|
|
166
|
+
const manage = home ? 'data-manage-connections' : 'data-page="connections"'
|
|
151
167
|
return `
|
|
152
168
|
<section class="pj-sec pj-s-tiles" data-apps>
|
|
153
|
-
<div class="sec-head"><h2>Connections</h2><span class="count">${v ? n : ''}</span><span class="hint"
|
|
154
|
-
<button type="button" class="btn sm ghost"
|
|
169
|
+
<div class="sec-head"><h2>Connections</h2><span class="count">${v ? n : ''}</span><span class="hint">${home ? 'Apps the agents in every project can use.' : "Apps this project's agents can use."}</span><span class="spacer"></span>
|
|
170
|
+
<button type="button" class="btn sm ghost" ${manage}>${I.gear}<span>Manage</span></button></div>
|
|
155
171
|
${v ? `<div class="pj-apps pj-cards">${own.map((c) => tile(c, true)).join('')}${above.map((c) => tile(c, false)).join('')}
|
|
156
|
-
${v.canManage ? `<button type="button" class="pj-app pj-slot"
|
|
172
|
+
${v.canManage ? `<button type="button" class="pj-app pj-slot" ${manage}><span class="pj-plus">${I.plus}</span><span>Connect an app</span></button>` : ''}</div>` : '<p class="hint">Loading connections…</p>'}
|
|
157
173
|
</section>`
|
|
158
174
|
}
|
|
159
175
|
|
|
@@ -168,6 +184,13 @@ function sideHtml (p, d, page) {
|
|
|
168
184
|
const nav = (v, icon, label, n) => `<button type="button" class="${page === v ? 'on' : ''}" data-page="${v}"${page === v ? ' aria-current="page"' : ''}>${icon}<span class="nm">${label}</span>${n === undefined ? '' : `<span class="ct">${n}</span>`}</button>`
|
|
169
185
|
const isFolded = (k) => foldedNow().has(k)
|
|
170
186
|
const label = (k, text, n, extra = '') => `<div class="side-label pj-side-label"><button type="button" class="pj-fold" data-fold="${k}" aria-expanded="${!isFolded(k)}" title="${isFolded(k) ? 'Show' : 'Hide'} ${text.toLowerCase()}"><span>${text}</span>${I.chevDown}</button>${isFolded(k) && n ? `<span class="ct">${n}</span>` : ''}${extra}</div>`
|
|
187
|
+
// Channels: the project's own (kept by the accounts API), then one for each codebase open here (its chat).
|
|
188
|
+
const open = list.filter((c) => c.where === 'open')
|
|
189
|
+
const own = channelUnread(p.id)
|
|
190
|
+
const newHere = own + open.reduce((n, c) => n + ((state.sessions.get(c.id)?.status.unread) || 0), 0)
|
|
191
|
+
const room = (attrs, name, n, on) => `<button type="button" class="${on ? 'on' : ''}" ${attrs}${on ? ' aria-current="page"' : ''}><span class="pj-hash">#</span><span class="nm">${esc(name)}</span>${n ? `<span class="ct new">${n > 99 ? '99+' : n}</span>` : ''}</button>`
|
|
192
|
+
// Direct messages, across the codebases open here: a row opens that codebase's chat on them.
|
|
193
|
+
const dms = projectDms(open.map((c) => ({ id: c.id, name: c.name, messages: state.messages.get(c.id) || [], me: state.sessions.get(c.id)?.status.me?.name || '' })))
|
|
171
194
|
const row = (c) => {
|
|
172
195
|
const act = c.where === 'open' ? `data-go="${esc(c.id)}"` : c.where === 'here' ? `data-rejoin="${esc(c.dir)}"` : `data-join-room="${esc(c.room)}" data-name="${esc(c.name)}"`
|
|
173
196
|
const say = c.where === 'away' ? 'Not on this computer yet: join it' : `Open ${c.name}${c.dir ? ` (${c.dir})` : ''}`
|
|
@@ -178,6 +201,12 @@ function sideHtml (p, d, page) {
|
|
|
178
201
|
<nav class="side-nav" aria-label="Pages">${nav('', I.grid, 'Overview')}${nav('tasks', I.board, 'Tasks', projectOpenTasks(d))}${nav('artifacts', I.folder, 'Artifacts', files)}${state.connectionsOn ? nav('connections', I.link, 'Connections') : ''}</nav>
|
|
179
202
|
${label('codebases', 'Codebases', list.length, d.access?.access === 'edit' ? `<button type="button" class="btn sm ghost icon" data-new-codebase title="New codebase" aria-label="New codebase">${I.plus}</button>` : '')}
|
|
180
203
|
<div class="side-sessions">${isFolded('codebases') ? '' : list.map(row).join('')}</div>
|
|
204
|
+
${label('channels', 'Channels', newHere)}
|
|
205
|
+
<div class="side-sessions pj-rooms">${isFolded('channels') && page !== 'channel' && !newHere ? '' : `
|
|
206
|
+
${room(`data-page="channel" title="Everyone in ${esc(p.name)}"`, p.name, own, page === 'channel')}
|
|
207
|
+
${isFolded('channels') ? '' : open.map((c) => room(`data-go-chat="${esc(c.id)}" title="Everyone working in ${esc(c.name)}"`, c.name, (state.sessions.get(c.id)?.status.unread) || 0, false)).join('')}`}</div>
|
|
208
|
+
${dms.length ? `${label('dms', 'Direct messages')}
|
|
209
|
+
<div class="side-sessions pj-rooms">${isFolded('dms') ? '' : dms.map((t) => `<button type="button" data-go-dm="${esc(t.code)}" data-name="${esc(t.name)}" title="You and ${esc(t.name)}, in ${esc(t.codeName)}">${avatar(t.name)}<span class="nm">${esc(t.name)}</span></button>`).join('')}</div>` : ''}
|
|
181
210
|
<div class="side-foot side-nav">
|
|
182
211
|
<button type="button" data-team title="People and agents in this project"><span class="pj-faces sm">${team.slice(0, 3).map((m) => avatar(m.name)).join('')}</span><span class="nm">Team</span><span class="ct">${count}</span></button>
|
|
183
212
|
${d.access?.admin ? `<button type="button" data-invite-project>${I.link}<span class="nm">Invite</span></button>` : ''}
|
|
@@ -201,16 +230,19 @@ export function codeCrumbHtml (project) {
|
|
|
201
230
|
* `tasks`: its open tasks; `artifacts`: how many the project has, once known; `chatNew`: messages in its channel since it was last looked at;
|
|
202
231
|
* `people`: who is in it, you first ({ name, color }).
|
|
203
232
|
*/
|
|
204
|
-
export function codeSideHtml ({ page, name, project, tasks = 0, artifacts = 0, chatNew = 0, people = [], connections = false, canInvite = true }) {
|
|
233
|
+
export function codeSideHtml ({ page, name, project, tasks = 0, artifacts = 0, chatNew = 0, people = [], connections = false, canInvite = true, dms = [], dmOn = '' }) {
|
|
205
234
|
const nav = (v, icon, label, n, attr = `data-code-page="${v}"`) => `<button type="button" class="${page === v ? 'on' : ''}" ${attr}${page === v ? ' aria-current="page"' : ''}>${icon}<span class="nm">${label}</span>${n ? `<span class="ct">${n}</span>` : ''}</button>`
|
|
206
235
|
const isFolded = (k) => foldedNow().has(k)
|
|
207
236
|
const label = (k, text, n) => `<div class="side-label pj-side-label"><button type="button" class="pj-fold" data-fold="${k}" aria-expanded="${!isFolded(k)}" title="${isFolded(k) ? 'Show' : 'Hide'} ${text.toLowerCase()}"><span>${text}</span>${I.chevDown}</button>${isFolded(k) && n ? `<span class="ct new">${n}</span>` : ''}</div>`
|
|
208
237
|
// A folded section keeps the row you are on and what is new.
|
|
209
238
|
const channel = !isFolded('channels') || page === 'chat' || chatNew
|
|
239
|
+
const inDm = page === 'chat' ? dmOn : ''
|
|
210
240
|
return `
|
|
211
241
|
<nav class="side-nav" aria-label="Pages">${nav('loom', I.users, 'Loom')}${nav('tasks', I.board, 'Tasks', tasks)}${project ? nav('artifacts', I.folder, 'Artifacts', artifacts) : ''}${connections ? nav('connections', I.link, 'Connections') : ''}</nav>
|
|
212
242
|
${label('channels', 'Channels', chatNew)}
|
|
213
|
-
<div class="side-sessions pj-rooms">${channel ? `<button type="button" class="${page === 'chat' ? 'on' : ''}" data-code-page="chat" title="Everyone working in ${esc(name)}"${page === 'chat' ? ' aria-current="page"' : ''}><span class="pj-hash">#</span><span class="nm">${esc(name)}</span>${chatNew ? `<span class="ct new">${chatNew > 99 ? '99+' : chatNew}</span>` : ''}</button>` : ''}</div>
|
|
243
|
+
<div class="side-sessions pj-rooms">${channel ? `<button type="button" class="${page === 'chat' && !inDm ? 'on' : ''}" data-code-page="chat" data-dm="" title="Everyone working in ${esc(name)}"${page === 'chat' && !inDm ? ' aria-current="page"' : ''}><span class="pj-hash">#</span><span class="nm">${esc(name)}</span>${chatNew ? `<span class="ct new">${chatNew > 99 ? '99+' : chatNew}</span>` : ''}</button>` : ''}</div>
|
|
244
|
+
${dms.length ? `${label('dms', 'Direct messages')}
|
|
245
|
+
<div class="side-sessions pj-rooms">${isFolded('dms') && !inDm && !dms.some((t) => t.n) ? '' : dms.filter((t) => !isFolded('dms') || t.name === inDm || t.n).map((t) => `<button type="button" class="${t.name === inDm ? 'on' : ''}" data-dm="${esc(t.name)}" title="You and ${esc(t.name)}"${t.name === inDm ? ' aria-current="page"' : ''}>${avatar(t.name)}<span class="nm">${esc(t.name)}</span>${t.n ? `<span class="ct new">${t.n > 99 ? '99+' : t.n}</span>` : ''}</button>`).join('')}</div>` : ''}
|
|
214
246
|
<div class="side-foot side-nav">
|
|
215
247
|
<button type="button" data-code-team title="People in this codebase"><span class="pj-faces sm">${people.slice(0, 3).map((m) => avatar(m.name, m.color)).join('')}</span><span class="nm">Team</span><span class="ct">${people.length}</span></button>
|
|
216
248
|
${canInvite ? `<button type="button" data-code-invite>${I.link}<span class="nm">Invite</span></button>` : ''}
|
|
@@ -235,11 +267,14 @@ function loadAgents (rerender) {
|
|
|
235
267
|
}).catch(() => { if (!state.placedAgents) { state.placedAgents = []; rerender() } })
|
|
236
268
|
}
|
|
237
269
|
|
|
270
|
+
let channelTimer = null
|
|
238
271
|
const appsAsked = new Map()
|
|
272
|
+
/** Where a page's connections are: a project's by its id, your own (Home) as 'me'. */
|
|
273
|
+
const appsUrl = (id, rest = '') => `/api/connections/${id === 'me' ? 'account/me' : `workspace/${encodeURIComponent(id)}`}${rest}`
|
|
239
274
|
function loadApps (id, rerender, { now = false } = {}) {
|
|
240
275
|
if (!now && Date.now() - (appsAsked.get(id) || 0) < 5000) return
|
|
241
276
|
appsAsked.set(id, Date.now())
|
|
242
|
-
api('GET',
|
|
277
|
+
api('GET', appsUrl(id)).then((v) => {
|
|
243
278
|
const was = JSON.stringify(apps.get(id) || null)
|
|
244
279
|
apps.set(id, v)
|
|
245
280
|
if (JSON.stringify(v) !== was) rerender()
|
|
@@ -248,7 +283,8 @@ function loadApps (id, rerender, { now = false } = {}) {
|
|
|
248
283
|
|
|
249
284
|
// ------------------------------------------------------------------ page --
|
|
250
285
|
function homePageHtml () {
|
|
251
|
-
return codebasesHtml(looseCodebases({ sessions: state.sessions, recent: state.recent, projects: state.workspaces || [] })) + homeAgentsHtml()
|
|
286
|
+
return codebasesHtml(looseCodebases({ sessions: state.sessions, recent: state.recent, projects: state.workspaces || [] })) + homeAgentsHtml() +
|
|
287
|
+
(state.connectionsOn ? appsSectionHtml(appsOf('me'), { home: true }) : '')
|
|
252
288
|
}
|
|
253
289
|
|
|
254
290
|
function projectPageHtml (p, view) {
|
|
@@ -263,10 +299,11 @@ function projectPageHtml (p, view) {
|
|
|
263
299
|
const page = pageOf(view)
|
|
264
300
|
const main = page === 'artifacts' ? artifactsHtml(d)
|
|
265
301
|
: page === 'tasks' ? '<div class="pj-board" data-project-board></div>'
|
|
302
|
+
: page === 'channel' ? '<div class="pj-chanpage" data-project-channel></div>'
|
|
266
303
|
: page === 'connections' ? `<div class="files-head"><div class="t"><h2 class="crumbs">Connections</h2><p class="hint">Apps this project's agents can use. Agents never see the logins.</p></div></div><div data-project-connections></div>`
|
|
267
304
|
: codebasesHtml(projectCodebases(d, state.sessions, `person:${state.account?.id}`), { project: p, canAdd: d.access?.access === 'edit' }) +
|
|
268
|
-
projectAgentsHtml(d) + (state.connectionsOn ?
|
|
269
|
-
return `${sideHtml(p, d, page)}<div class="pj-pmain${page === 'artifacts' ? ' pj-files' : page === 'tasks' ? ' pj-tasks' : ''}">${main}</div>`
|
|
305
|
+
projectAgentsHtml(d) + (state.connectionsOn ? appsSectionHtml(appsOf(p.id)) : '')
|
|
306
|
+
return `${sideHtml(p, d, page)}<div class="pj-pmain${page === 'artifacts' ? ' pj-files' : page === 'tasks' ? ' pj-tasks' : page === 'channel' ? ' pj-chat' : ''}">${main}</div>`
|
|
270
307
|
}
|
|
271
308
|
|
|
272
309
|
/** Home or a project's page, under the header, for `view` ('home', 'ws:<id>' or 'wsfiles:<id>'). */
|
|
@@ -337,6 +374,15 @@ export function bindProjectShell (view, { go, rerender, newSessionDialog, joinSe
|
|
|
337
374
|
} catch (err) { toast(err.message); box.checked = !box.checked }
|
|
338
375
|
}
|
|
339
376
|
})
|
|
377
|
+
// Connections as tiles (a project's, or your own on Home): the switch says whether agents may use one.
|
|
378
|
+
const appsId = p ? p.id : 'me'
|
|
379
|
+
if (root.querySelector('[data-apps]')) loadApps(appsId, rerender)
|
|
380
|
+
root.querySelectorAll('[data-app-who]').forEach((box) => {
|
|
381
|
+
box.onchange = async () => {
|
|
382
|
+
try { await api('PATCH', appsUrl(appsId, `/${encodeURIComponent(box.dataset.appWho)}`), { who: box.checked ? 'all' : 'people' }); loadApps(appsId, rerender, { now: true }) } catch (err) { toast(err.message); box.checked = !box.checked }
|
|
383
|
+
}
|
|
384
|
+
})
|
|
385
|
+
root.querySelectorAll('[data-manage-connections]').forEach((b) => { b.onclick = () => { state.settingsTab = 'connections'; openSettings() } })
|
|
340
386
|
if (!p) return
|
|
341
387
|
// The sidebar: its pages, closing it, folding a section.
|
|
342
388
|
const side = $('#pj-side-btn')
|
|
@@ -344,7 +390,7 @@ export function bindProjectShell (view, { go, rerender, newSessionDialog, joinSe
|
|
|
344
390
|
root.querySelectorAll('[data-page]').forEach((b) => {
|
|
345
391
|
b.onclick = () => {
|
|
346
392
|
const page = b.dataset.page
|
|
347
|
-
state.projectPage = page === 'connections' || page === 'tasks' ? page : ''
|
|
393
|
+
state.projectPage = page === 'connections' || page === 'tasks' || page === 'channel' ? page : ''
|
|
348
394
|
const to = page === 'artifacts' ? `wsfiles:${p.id}` : `ws:${p.id}`
|
|
349
395
|
if (to === state.view) rerender(); else go(to)
|
|
350
396
|
}
|
|
@@ -359,11 +405,29 @@ export function bindProjectShell (view, { go, rerender, newSessionDialog, joinSe
|
|
|
359
405
|
if (!d || d.workspace.id !== p.id) return
|
|
360
406
|
const main = root.querySelector('.pj-pmain')
|
|
361
407
|
if (pageOf(view) === 'artifacts') bindAllFiles(main, { id: p.id, go, rerender, reload })
|
|
408
|
+
// The project's channel: asked for every few seconds while this project's page is open, so what is new shows with no codebase open.
|
|
409
|
+
// What is new changed: the sidebar says so. With the channel itself open only its count is touched, so what is being typed stays.
|
|
410
|
+
const newCount = () => {
|
|
411
|
+
if (state.view !== view) return
|
|
412
|
+
if (!root.querySelector('[data-project-channel]')) return rerender()
|
|
413
|
+
const row = root.querySelector('[data-page="channel"]'); const n = channelUnread(p.id)
|
|
414
|
+
if (!row) return
|
|
415
|
+
row.querySelector('.ct')?.remove()
|
|
416
|
+
if (n) row.insertAdjacentHTML('beforeend', `<span class="ct new">${n > 99 ? '99+' : n}</span>`)
|
|
417
|
+
}
|
|
418
|
+
clearInterval(channelTimer)
|
|
419
|
+
channelTimer = setInterval(() => { if (state.view !== view || !root.isConnected) return clearInterval(channelTimer); loadChannel(p.id, newCount) }, 4000)
|
|
420
|
+
loadChannel(p.id, newCount)
|
|
421
|
+
const channel = root.querySelector('[data-project-channel]')
|
|
422
|
+
if (channel) mountChannel(channel, { d, changed: newCount })
|
|
423
|
+
// A codebase's channel, or a direct message in it: the codebase opens on its chat.
|
|
424
|
+
root.querySelectorAll('[data-go-chat]').forEach((b) => { b.onclick = () => { state.openChat = b.dataset.goChat; state.to = ''; go(b.dataset.goChat) } })
|
|
425
|
+
root.querySelectorAll('[data-go-dm]').forEach((b) => { b.onclick = () => { state.openChat = b.dataset.goDm; state.to = b.dataset.name; go(b.dataset.goDm) } })
|
|
362
426
|
const board = root.querySelector('[data-project-board]')
|
|
363
427
|
// The open count beside Tasks follows the board as it changes.
|
|
364
428
|
if (board) mountProjectBoard(board, { d, go, reload, changed: () => { const ct = root.querySelector('[data-page="tasks"] .ct'); if (ct) ct.textContent = projectOpenTasks(state.workspace) } })
|
|
365
429
|
const conns = root.querySelector('[data-project-connections]')
|
|
366
|
-
if (conns) mountConnections(conns, { type: 'workspace', id: p.id })
|
|
430
|
+
if (conns) mountConnections(conns, { type: 'workspace', id: p.id, agents: () => ((state.workspace && state.workspace.agents) || []).filter((a) => a.agentId).map((a) => ({ id: a.agentId, name: a.name })) })
|
|
367
431
|
// An agent's switch in this project: one added here keeps its place and changes whether it is invited; one from above gets this project's own setting.
|
|
368
432
|
root.querySelectorAll('[data-agent-here]').forEach((box) => {
|
|
369
433
|
box.onchange = async () => {
|
|
@@ -379,12 +443,6 @@ export function bindProjectShell (view, { go, rerender, newSessionDialog, joinSe
|
|
|
379
443
|
}
|
|
380
444
|
})
|
|
381
445
|
// Connections: asked for when the overview shows them; a switch says whether agents may use one.
|
|
382
|
-
if (root.querySelector('[data-apps]')) loadApps(p.id, rerender)
|
|
383
|
-
root.querySelectorAll('[data-app-who]').forEach((box) => {
|
|
384
|
-
box.onchange = async () => {
|
|
385
|
-
try { await api('PATCH', `/api/connections/workspace/${encodeURIComponent(p.id)}/${encodeURIComponent(box.dataset.appWho)}`, { who: box.checked ? 'all' : 'people' }); loadApps(p.id, rerender, { now: true }) } catch (err) { toast(err.message); box.checked = !box.checked }
|
|
386
|
-
}
|
|
387
|
-
})
|
|
388
446
|
}
|
|
389
447
|
|
|
390
448
|
/** Moves a codebase on this computer into a project you can edit, picked from a list. */
|
package/src/ui/session.js
CHANGED
|
@@ -28,6 +28,7 @@ import { renderCatchUp, bindCatchUp } from './catchup.js'
|
|
|
28
28
|
import { heldCard } from './session-words.js'
|
|
29
29
|
import { callButtonMarkup, callPinMarkup, screenStageMarkup, mountCall, unmountCall, renderCall, callCards, inCallHere } from './voice.js'
|
|
30
30
|
import { codeSideHtml, codeCrumbHtml, sideShut, toggleSideShut, toggleFolded } from './projects.js'
|
|
31
|
+
import { dmThreads } from './project-model.js'
|
|
31
32
|
|
|
32
33
|
let current = null // session id being shown
|
|
33
34
|
let timers = []
|
|
@@ -106,6 +107,8 @@ function personInfo (name) {
|
|
|
106
107
|
// ------------------------------------------------------------------ mount --
|
|
107
108
|
export function mountSession (id) {
|
|
108
109
|
current = id
|
|
110
|
+
// Opened from a channel or a direct message in the project's sidebar: on its chat.
|
|
111
|
+
if (state.openChat === id) { ws(id).side = 'chat'; state.openChat = null }
|
|
109
112
|
pendingAssign = null
|
|
110
113
|
resetLoom()
|
|
111
114
|
boardQuery = '' // a search is for the board it was typed on
|
|
@@ -399,7 +402,7 @@ function renderCodeSide () {
|
|
|
399
402
|
const page = side || (w.mode === 'tasks' ? 'tasks' : 'loom')
|
|
400
403
|
const open = (st.tasks || []).filter((t) => !t.archived && (t.column === 'todo' || t.column === 'doing')).length
|
|
401
404
|
const people = [st.me, ...peopleHere(st)]
|
|
402
|
-
el.innerHTML = codeSideHtml({ page, name: st.sessionName || basename(sum().dir), project: projectHere(), tasks: open, artifacts: (projectData()?.files || []).filter((f) => f.kind !== 'folder').length, chatNew, people, connections: !!state.connectionsOn, canInvite: !!st.access?.owner || st.access?.role !== 'viewer' })
|
|
405
|
+
el.innerHTML = codeSideHtml({ page, name: st.sessionName || basename(sum().dir), project: projectHere(), tasks: open, artifacts: (projectData()?.files || []).filter((f) => f.kind !== 'folder').length, chatNew, people, dms: dmThreads(renderable(state.messages.get(current)), st.me?.name || '').map((t) => ({ ...t, n: dmNew.get(t.name) || 0 })), dmOn: state.to || '', connections: !!state.connectionsOn, canInvite: !!st.access?.owner || st.access?.role !== 'viewer' })
|
|
403
406
|
const root = $('#ws')
|
|
404
407
|
root.dataset.sidePage = side
|
|
405
408
|
$('#code-crumb').innerHTML = codeCrumbHtml(projectHere())
|
|
@@ -465,6 +468,8 @@ function bindCodeSide () {
|
|
|
465
468
|
el.addEventListener('click', (e) => {
|
|
466
469
|
const b = e.target.closest('button')
|
|
467
470
|
if (!b || !el.contains(b)) return
|
|
471
|
+
// The channel is for everyone; a direct message's row is that person alone.
|
|
472
|
+
if (b.dataset.dm !== undefined) { state.to = b.dataset.dm; showCodePage('chat'); renderRecipients(); updatePlaceholder(); return renderCodeSide() }
|
|
468
473
|
if (b.dataset.codePage) return showCodePage(b.dataset.codePage)
|
|
469
474
|
if (b.dataset.fold) { toggleFolded(b.dataset.fold); return renderCodeSide() }
|
|
470
475
|
if (b.dataset.go) return go(b.dataset.go)
|
|
@@ -2442,6 +2447,7 @@ const CHAT_MAX = 640
|
|
|
2442
2447
|
const CHAT_SNAP = 220
|
|
2443
2448
|
let chatSeenTs = Date.now() // messages after this count on the folded rail
|
|
2444
2449
|
let chatNew = 0 // how many of them there are, for the sidebar's channel row
|
|
2450
|
+
let dmNew = new Map() // and for each direct message's row: who wrote -> how many
|
|
2445
2451
|
|
|
2446
2452
|
// With the sidebar (projects on), chat is a page from the sidebar, not a column: it counts as folded
|
|
2447
2453
|
// whenever it is not the page showing (a call keeps it beside the page).
|
|
@@ -2473,13 +2479,19 @@ function renderChatBadge () {
|
|
|
2473
2479
|
const rail = $('#chat-rail')
|
|
2474
2480
|
const s = sum()
|
|
2475
2481
|
if (!badge || !rail) return
|
|
2476
|
-
const
|
|
2477
|
-
? renderable(state.messages.get(current)).filter((m) => (m.ts || 0) > chatSeenTs && shownName(m.by, owners(s)) !== s.status.me?.name && !ownAiChatter(m, owners(s)))
|
|
2478
|
-
:
|
|
2482
|
+
const fresh = s && chatCollapsed()
|
|
2483
|
+
? renderable(state.messages.get(current)).filter((m) => (m.ts || 0) > chatSeenTs && shownName(m.by, owners(s)) !== s.status.me?.name && !ownAiChatter(m, owners(s)))
|
|
2484
|
+
: []
|
|
2485
|
+
// With the sidebar, what was written to you alone counts on its own row, the rest on the channel's.
|
|
2486
|
+
const direct = new Map()
|
|
2487
|
+
if (pj()) for (const m of fresh) if (m.to) direct.set(m.by, (direct.get(m.by) || 0) + 1)
|
|
2488
|
+
const n = pj() ? fresh.filter((m) => !m.to).length : fresh.length
|
|
2489
|
+
const dmChanged = JSON.stringify([...direct]) !== JSON.stringify([...dmNew])
|
|
2490
|
+
dmNew = direct
|
|
2479
2491
|
badge.hidden = !n
|
|
2480
2492
|
badge.textContent = n > 99 ? '99+' : String(n)
|
|
2481
2493
|
rail.title = n ? `Open chat · ${n} new message${n === 1 ? '' : 's'}` : 'Open chat'
|
|
2482
|
-
if (n !== chatNew) { chatNew = n; renderCodeSide() }
|
|
2494
|
+
if (n !== chatNew || dmChanged) { chatNew = n; renderCodeSide() }
|
|
2483
2495
|
}
|
|
2484
2496
|
|
|
2485
2497
|
function bindChatPane () {
|
|
@@ -2832,8 +2844,10 @@ function renderMessages (incoming = false, force = false) {
|
|
|
2832
2844
|
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80
|
|
2833
2845
|
const who = owners(s)
|
|
2834
2846
|
// A person's AI sessions working things out among themselves isn't shown: only what they say to people.
|
|
2835
|
-
const
|
|
2847
|
+
const every = renderable(state.messages.get(current)).filter((m) => !ownAiChatter(m, who)) // peers can push anything into the room
|
|
2836
2848
|
const name = s.status.me.name
|
|
2849
|
+
// With the sidebar, a direct message's row shows that conversation alone, and the channel what was said to everyone.
|
|
2850
|
+
const list = !pj() ? every : state.to ? every.filter((m) => m.to && ((m.by === state.to && m.to === name) || (m.to === state.to && shownName(m.by, who) === name))) : every.filter((m) => !m.to)
|
|
2837
2851
|
const colors = new Map(s.status.peers.map((p) => [p.name, p.color]))
|
|
2838
2852
|
colors.set(name, s.status.me.color)
|
|
2839
2853
|
const names = mentionNames(s)
|
package/src/ui-server.js
CHANGED
|
@@ -21,6 +21,7 @@ import { autowork, autoConfig, publicConfig, AUTO_MODES } from './autowork.js'
|
|
|
21
21
|
import { migrateDir } from './legacy.js'
|
|
22
22
|
import { writePrivateJson } from './private-file.js'
|
|
23
23
|
import { autoToolFor } from './autowork-tools.js'
|
|
24
|
+
import { workspaceMessages, sayInWorkspace, readWorkspaceMessages } from './account.js'
|
|
24
25
|
import { readAccount, saveAccount, clearAccount, clearAccountIf, resumeAccount, startLink, waitForLink, signUpForLink, confirmSignUpForLink, fetchMe, signOut, revokeToken, accountFromProfile, renameSession, createAgentInvite, listAgents, agentDetails, listAccessTypes, listCollaborators, listGrants, putGrant, deleteGrant, inviteToSession, listSessionInvites, cancelSessionInvite, listWorkspaces, listOrgs, createWorkspace, getWorkspace, updateWorkspace, deleteWorkspace, putWorkspaceMember, removeWorkspaceMember, getAgentPlacement, putAgentPlacement, listOrgAgents, putWorkspaceAgent, deleteWorkspaceAgent, createWorkspaceAgentInvite, excludeSessionAgent, listExcludedSessionAgents, listSessionAgents, includeSessionAgent, setSessionWorkspace, moveSessionToWorkspace, listWorkspaceInvites, inviteToWorkspace, cancelWorkspaceInvite, listMyInvites, answerMyInvite, listMySessions, announceSessionStarted, announceWhenReported, listWorkspaceFiles, createWorkspaceFile, confirmWorkspaceFile, workspaceFileDownload, updateWorkspaceFile, deleteWorkspaceFile, createWorkspaceFolder, listWorkspaceFileVersions, listSandboxKeys, createSandboxKey, rotateSandboxKey, revokeSandboxKey, removeSandboxKey, aiVmFollow, aiVmUnfollow, aiVmStatus, aiVmConnect, aiVmUpdate, aiVmSignIn, aiVmWake, aiVmDisconnect, voiceIce, transcribeVoice, speakVoice, speakVoiceStream, apiUrl } from './account.js'
|
|
25
26
|
import { aiName } from './persona.js'
|
|
26
27
|
import { effectiveAccess, builtinType } from './session-access.js'
|
|
@@ -186,6 +187,7 @@ export const STATIC = {
|
|
|
186
187
|
'/project-model.js': ['project-model.js', 'text/javascript; charset=utf-8'],
|
|
187
188
|
'/project-board.js': ['project-board.js', 'text/javascript; charset=utf-8'],
|
|
188
189
|
'/project-pop.js': ['project-pop.js', 'text/javascript; charset=utf-8'],
|
|
190
|
+
'/project-channel.js': ['project-channel.js', 'text/javascript; charset=utf-8'],
|
|
189
191
|
'/prail.js': ['prail.js', 'text/javascript; charset=utf-8'],
|
|
190
192
|
'/prail-model.js': ['prail-model.js', 'text/javascript; charset=utf-8'],
|
|
191
193
|
'/rail-model.js': ['rail-model.js', 'text/javascript; charset=utf-8'],
|
|
@@ -1010,12 +1012,13 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
1010
1012
|
return asAccount(async (token) => {
|
|
1011
1013
|
const c = secretsApi(token)
|
|
1012
1014
|
if (method === 'GET' && p === '/api/connections/apps') return apiCall(c, 'GET', `/v1/connections/apps?search=${enc(url.searchParams.get('search') || '')}&limit=${enc(url.searchParams.get('limit') || '60')}`)
|
|
1013
|
-
const sc = p.match(/^\/api\/connections\/(org|workspace|session)\/([^/]+)(?:\/([0-9a-f-]{36}))?$/i)
|
|
1014
|
-
|
|
1015
|
+
const sc = p.match(/^\/api\/connections\/(org|workspace|session|account)\/([^/]+)(?:\/([0-9a-f-]{36}))?$/i)
|
|
1016
|
+
// A person's own connections are always "me": the accounts API reads who from the sign-in.
|
|
1017
|
+
if (sc && (sc[1] === 'account' ? sc[2] === 'me' : SECRET_SCOPE_ID[sc[1]].test(decodeURIComponent(sc[2])))) {
|
|
1015
1018
|
const base = `/v1/connections/${sc[1]}/${enc(decodeURIComponent(sc[2]))}`
|
|
1016
1019
|
if (!sc[3] && method === 'GET') return apiCall(c, 'GET', base)
|
|
1017
1020
|
if (!sc[3] && method === 'POST') return apiCall(c, 'POST', base, { app: String(body.app || ''), ...(body.who ? { who: String(body.who) } : {}) })
|
|
1018
|
-
if (sc[3] && method === 'PATCH') return apiCall(c, 'PATCH', `${base}/${sc[3]}`, { who: String(body.who || '') })
|
|
1021
|
+
if (sc[3] && method === 'PATCH') return apiCall(c, 'PATCH', `${base}/${sc[3]}`, { who: String(body.who || ''), ...(Array.isArray(body.agents) ? { agents: body.agents.map(String).slice(0, 100) } : {}) })
|
|
1019
1022
|
if (sc[3] && method === 'DELETE') return apiCall(c, 'DELETE', `${base}/${sc[3]}`)
|
|
1020
1023
|
}
|
|
1021
1024
|
const calls = p.match(/^\/api\/app-calls\/([A-Za-z0-9_-]{1,64})(?:\/([0-9a-f-]{36}))?$/i)
|
|
@@ -1150,6 +1153,10 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
1150
1153
|
'GET /api/invites': () => asAccount(async (token) => ({ invites: (await listMyInvites({ token })).filter((i) => i.kind !== 'workspace' || appWorkspaces()) })),
|
|
1151
1154
|
'POST /api/invites/:id/accept': (b, id) => asAccount(async (token) => answerMyInvite({ token, id: needInviteId(id), how: 'accept' })),
|
|
1152
1155
|
'POST /api/invites/:id/decline': (b, id) => asAccount(async (token) => answerMyInvite({ token, id: needInviteId(id), how: 'decline' })),
|
|
1156
|
+
// A project's channel: kept by the accounts API, so it is there with no codebase open.
|
|
1157
|
+
'GET /api/workspaces/:id/messages': (b, id, url) => asAccount((token) => workspaceMessages({ token, id: needWorkspaceId(id), after: Number(url.searchParams.get('after')) || 0 })),
|
|
1158
|
+
'POST /api/workspaces/:id/messages': (b, id) => asAccount((token) => sayInWorkspace({ token, id: needWorkspaceId(id), text: String(b.text || '').slice(0, 8000) })),
|
|
1159
|
+
'POST /api/workspaces/:id/messages/read': (b, id) => asAccount((token) => readWorkspaceMessages({ token, id: needWorkspaceId(id) })),
|
|
1153
1160
|
'GET /api/workspaces/:id/files': (b, id, url) => asAccount(async (token) => ({ files: await listWorkspaceFiles({ token, id: needWorkspaceId(id), folder: url.searchParams.get('folder') ?? undefined }) })),
|
|
1154
1161
|
'GET /api/workspaces/:id/files/:fid/versions': (b, id, url, fid) => asAccount(async (token) => ({ versions: await listWorkspaceFileVersions({ token, id: needWorkspaceId(id), fileId: fid }) })),
|
|
1155
1162
|
// The address an HTML artifact's frame loads (serveSealed): asked for by the page, with its token.
|