workspaceRoutes.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  6. import { randomUUID } from 'node:crypto'
  7. import request from 'supertest'
  8. import type Koa from 'koa'
  9. import { createApplication, type ApplicationRuntime } from '../../src/server/app'
  10. import { loadServerConfig } from '../../src/server/config'
  11. import { LocalAuthStore, type LocalUser } from '../../src/server/localAuth'
  12. import { WorkspaceAssets } from '../../src/server/workspaceAssets'
  13. let home: string, runtime: ApplicationRuntime, cookie: string, csrf: string, upstream: string[], bridgeReady: boolean
  14. const first: LocalUser = {
  15. id: 'first',
  16. username: 'first',
  17. role: 'admin',
  18. enabled: true,
  19. mustChangePassword: false,
  20. createdAt: 1,
  21. updatedAt: 1,
  22. }
  23. class TestAuth extends LocalAuthStore {
  24. override current(ctx: Koa.Context) {
  25. return this.require(ctx)
  26. }
  27. override require(ctx: Koa.Context) {
  28. return { ...first, id: ctx.get('x-test-user') || 'first' }
  29. }
  30. override requireAdmin(ctx: Koa.Context) {
  31. return this.require(ctx)
  32. }
  33. override canUseSource() { return true }
  34. override currentFromCookieHeader() {
  35. return first
  36. }
  37. override isUserActive() {
  38. return true
  39. }
  40. }
  41. function req(method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, user = 'first') {
  42. return request(runtime.app.callback())
  43. [method](path)
  44. .set('Host', '127.0.0.1:15300')
  45. .set('Origin', 'http://127.0.0.1:15300')
  46. .set('Cookie', cookie)
  47. .set('X-CSRF-Token', csrf)
  48. .set('x-test-user', user)
  49. }
  50. beforeEach(async () => {
  51. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-routes-'))
  52. upstream = []
  53. bridgeReady = false
  54. const config = loadServerConfig({
  55. HERMES_YAOYAO_HOME: home,
  56. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:19119',
  57. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  58. })
  59. runtime = createApplication({
  60. config,
  61. auth: new TestAuth(home, false),
  62. fetchImpl: (async (input) => {
  63. const path = new URL(String(input)).pathname
  64. upstream.push(path)
  65. const body =
  66. path === '/api/plugins/yaoyao-bot-bridge/capabilities' && bridgeReady
  67. ? {version:1,ready:true,in_process:true,native_tools:true}
  68. : path === '/api/pair/v1/capabilities'
  69. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64)}
  70. : path === '/api/pair/v1/claim'
  71. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64),deviceId:'22222222-2222-4222-8222-222222222222',token:'delegated-token',scopes:['agents.read','sessions.execute','history.read'],serverUrl:'http://child.test:15300/node/22222222-2222-4222-8222-222222222222'}
  72. : path === '/api/status'
  73. ? { auth_required: true }
  74. : path === '/api/auth/me'
  75. ? { user_id: 'upstream' }
  76. : path.endsWith('/api/profiles')
  77. ? { profiles: [{ name: 'default', display_name: '基础 Agent' }] }
  78. : { ok: true }
  79. return new Response(JSON.stringify(body), {
  80. status: path.includes('/plugins/') && !bridgeReady ? 404 : 200,
  81. headers: { 'Content-Type': 'application/json' },
  82. })
  83. }) as typeof fetch,
  84. })
  85. const b = await request(runtime.app.callback())
  86. .get('/api/app/bootstrap')
  87. .set('Host', '127.0.0.1:15300')
  88. .expect(200)
  89. cookie = (b.headers['set-cookie'] as unknown as string[]).map((v) => v.split(';')[0]).join('; ')
  90. csrf = b.body.csrfToken
  91. })
  92. afterEach(() => {
  93. runtime.close()
  94. rmSync(home, { recursive: true, force: true })
  95. })
  96. describe('application workspace HTTP contract', () => {
  97. it('deletes only archived owned chats, clears their records, and preserves library files and members', async () => {
  98. const store = runtime.workspace
  99. const lead = store.createAgent('first', { name: '负责人', profile: 'default' })
  100. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  101. const group = store.createGroup('first', { name: '待删除群聊', memberIds: [lead.id, member.id], administratorId: lead.id })
  102. const task = store.tasks('first', group.id)[0]!
  103. const path = `/api/app/conversations/${group.id}`
  104. await req('delete', path).expect(409)
  105. store.updateConversation('first', group.id, { archived: true })
  106. store.put('second', 'conversation', group.id, group)
  107. for (const kind of ['message', 'run', 'turn', 'interaction', 'interaction-binding', 'binding', 'assignment']) {
  108. store.put('first', kind, kind, { id: kind, conversationId: group.id, conversationTaskId: task.id, status: 'complete' })
  109. store.put('second', kind, kind, { id: kind, conversationId: group.id })
  110. }
  111. store.put('first', 'context', task.id, { used: 5 })
  112. const bindingKey = `${group.id}:${task.id}:${lead.id}`
  113. store.put('first', 'binding', bindingKey, { conversationTaskId: task.id, sessionId: 'session' })
  114. store.put('first', 'interaction-binding', 'legacy-interaction', { key: bindingKey, taskId: 'turn' })
  115. store.put('second', 'binding', bindingKey, { sessionId: 'other-session' })
  116. store.put('first', 'file', 'file', { id: 'file', conversationId: group.id, messageId: 'message', name: '保留.txt' })
  117. await req('delete', path, 'third').expect(404)
  118. await req('delete', path).set('X-CSRF-Token', 'invalid').expect(403)
  119. await req('delete', path).expect(200)
  120. await req('get', path).expect(404)
  121. expect(store.get('first', 'context', task.id)).toBeUndefined()
  122. expect(store.get('first', 'conversation-task', task.id)).toBeUndefined()
  123. expect(store.list('first', 'message')).toEqual([])
  124. expect(store.list('first', 'run')).toEqual([])
  125. expect(store.list('first', 'binding')).toEqual([])
  126. expect(store.list('first', 'interaction-binding')).toEqual([])
  127. expect(store.get('second', 'binding', bindingKey)).toEqual({ sessionId: 'other-session' })
  128. expect(store.get('first', 'file', 'file')).toEqual({ id: 'file', name: '保留.txt' })
  129. expect(store.list('first', 'agent')).toHaveLength(2)
  130. expect(store.get('second', 'conversation', group.id)).toEqual(group)
  131. expect(store.get('second', 'message', 'message')).toBeDefined()
  132. expect((await req('get', '/api/app/events')).body.events.some((e: any) => e.type === 'conversation.deleted' && e.conversationId === group.id)).toBe(true)
  133. })
  134. it('deletes an archived Bot and its direct chat only after group references are removed', async () => {
  135. const store = runtime.workspace
  136. const bot = store.createAgent('first', { name: '归档 Bot', profile: 'default' })
  137. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  138. const direct = store.list<any>('first', 'conversation').find(c => c.memberIds[0] === bot.id)!
  139. const group = store.createGroup('first', { name: '关联群', memberIds: [bot.id, member.id], administratorId: member.id })
  140. const path = `/api/app/agents/${bot.id}`
  141. await req('delete', path).expect(409)
  142. store.updateAgent('first', bot.id, { archived: true })
  143. await req('delete', `/api/app/conversations/${direct.id}`).expect(400)
  144. expect((await req('delete', path).expect(409)).body.code).toBe('agent_in_group')
  145. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  146. store.updateConversation('first', group.id, { memberIds: [member.id] })
  147. await req('delete', path, 'second').expect(404)
  148. await req('delete', path).expect(200)
  149. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  150. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  151. expect(store.get('first', 'conversation', group.id)).toBeDefined()
  152. expect(store.get('first', 'agent', member.id)).toBeDefined()
  153. })
  154. it('keeps archived chats intact while runs or delegated goals are unresolved', async () => {
  155. const store = runtime.workspace
  156. const bot = store.createAgent('first', { name: '运行中', profile: 'default' })
  157. const direct = store.list<any>('first', 'conversation')[0]!
  158. store.updateAgent('first', bot.id, { archived: true })
  159. store.put('first', 'run', 'pending', { id: 'pending', conversationId: direct.id, status: 'uncertain' })
  160. const path = `/api/app/agents/${bot.id}`
  161. await req('delete', path).expect(409)
  162. expect(store.get('first', 'conversation', direct.id)).toBeDefined()
  163. store.remove('first', 'run', 'pending')
  164. store.put('first', 'goal', 'delegated', { id: 'delegated', conversationId: 'another-chat', origin: { conversationId: direct.id }, status: 'waiting' })
  165. await req('delete', path).expect(409)
  166. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  167. })
  168. it('resumes a stopped goal from a real user request without duplicating its run',async()=>{
  169. vi.spyOn(runtime.workspaceRuntime,'wake').mockImplementation(()=>{})
  170. vi.spyOn(runtime.workspaceRuntime.teamTools,'requireAvailable').mockResolvedValue()
  171. const lead=runtime.workspace.createAgent('first',{name:'任务负责人',profile:'default',canManageTeam:true})
  172. const member=runtime.workspace.createAgent('first',{name:'成员',profile:'default'})
  173. const source=runtime.workspace.list<any>('first','conversation').find(c=>c.kind==='direct'&&c.memberIds[0]===lead.id)!
  174. const original=runtime.workspaceRuntime.send('first',source.id,{requestId:randomUUID(),content:'完成任务'})
  175. const team=runtime.workspace.createGroup('first',{name:'任务组',memberIds:[lead.id,member.id],administratorId:lead.id})
  176. const task=runtime.workspace.tasks('first',team.id)[0]!
  177. runtime.workspaceRuntime.tasks.begin('first',task,lead,'完成任务',{conversationId:source.id,runId:original.id,agentId:lead.id})
  178. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/stop`).send({}).expect(200)
  179. const input={requestId:randomUUID()}
  180. const resumed=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  181. expect(resumed.body.goal.status).toBe('running')
  182. const repeated=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  183. expect(repeated.body.run.id).toBe(resumed.body.run.id)
  184. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`,'second').send({requestId:randomUUID()}).expect(404)
  185. })
  186. it('grants team management only with a ready bridge and persists explicit revocation', async () => {
  187. const denied = await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(409)
  188. expect(denied.body.code).toBe('team_tools_unavailable')
  189. expect((await req('get','/api/app/agents')).body.agents).toEqual([])
  190. bridgeReady = true
  191. const agent = (await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(201)).body.agent
  192. expect(agent.canManageTeam).toBe(true)
  193. await req('patch',`/api/app/agents/${agent.id}`,'second').send({canManageTeam:false}).expect(404)
  194. bridgeReady = false
  195. const disabled = await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:false}).expect(200)
  196. expect(disabled.body.agent.canManageTeam).toBe(false)
  197. expect((await req('get','/api/app/agents')).body.agents[0].canManageTeam).toBe(false)
  198. await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:true}).expect(409)
  199. })
  200. it('accepts only child pairing, hides credentials, and scopes address edits to the owner', async () => {
  201. const code = new URL('yaoyao://pair')
  202. for (const [key,value] of Object.entries({v:'1',url:'http://child.test:15300',node:'11111111-1111-4111-8111-111111111111',id:'33333333-3333-4333-8333-333333333333',fingerprint:'f'.repeat(64),secret:'s'.repeat(64)})) code.searchParams.set(key,value)
  203. await req('post','/api/app/nodes').send({name:'legacy',url:'http://child.test:9119',username:'user',password:'password'}).expect(400)
  204. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href.replace('://pair','://login')}).expect(400)
  205. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href}).expect(201)
  206. const listing=await req('get','/api/app/nodes').expect(200), node=listing.body.nodes[0]
  207. expect(node.transport).toBe('paired-web'); expect(JSON.stringify(listing.body)).not.toContain('delegated-token'); expect(node.secret).toBeUndefined()
  208. expect((await req('get','/api/app/nodes','second').expect(200)).body.nodes).toEqual([])
  209. await req('patch',`/api/app/nodes/${node.id}`,'second').send({name:'other',url:'http://new-ip.test:15300'}).expect(404)
  210. await req('patch',`/api/app/nodes/${node.id}`).send({name:'new name',url:'http://new-ip.test:15300'}).expect(200)
  211. const updated=(await req('get','/api/app/nodes').expect(200)).body.nodes[0]
  212. expect(updated.id).toBe(node.id); expect(updated.url).toBe('http://new-ip.test:15300/')
  213. const sources=(await req('get','/api/app/agents/sources').expect(200)).body.sources
  214. expect(sources.some((s:any)=>s.nodeId===node.id && s.profile==='default')).toBe(true)
  215. })
  216. it('archives native-chat uploads through the standard file API with user ownership', async () => {
  217. const assets = new WorkspaceAssets(runtime.workspace, runtime.workspaceRuntime.nodes, home)
  218. await assets.archiveText(
  219. 'first',
  220. '{"path":"/tmp/native-upload.txt"}',
  221. 'local',
  222. 'default',
  223. 'native-session',
  224. 'native-message',
  225. 'user',
  226. )
  227. const page = await req('get', '/api/app/files').expect(200)
  228. expect(page.body.items[0]).toMatchObject({
  229. name: 'native-upload.txt',
  230. sender: 'user',
  231. profile: 'default',
  232. })
  233. expect(upstream).toContain('/api/files/download')
  234. expect((await req('get', '/api/app/files', 'second')).body.items).toEqual([])
  235. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  236. })
  237. it('works without plugin discovery, installation, or any plugin HTTP request', async () => {
  238. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  239. expect(capabilities).toContain('editableGroups')
  240. expect(capabilities).not.toContain('immutableGroups')
  241. await req('get', '/api/app/files').expect(200)
  242. await req('get', '/api/app/voice/runtime').expect(200)
  243. await req('get', '/api/app/system/update/status').expect(200)
  244. await req('post', '/api/app/plugins/yaoyao/reconcile').send({}).expect(410)
  245. await req('get', '/api/plugins/yaoyao/v1/capabilities').expect(410)
  246. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  247. })
  248. it('changes members over HTTP while protecting the administrator and ownership', async () => {
  249. const a = (
  250. await req('post', '/api/app/agents').send({ name: '编辑', profile: 'default' }).expect(201)
  251. ).body.agent
  252. const b = (
  253. await req('post', '/api/app/agents').send({ name: '审查', profile: 'default' }).expect(201)
  254. ).body.agent
  255. const c = (
  256. await req('post', '/api/app/conversations')
  257. .send({ name: '团队', memberIds: [a.id, b.id], administratorId: a.id })
  258. .expect(201)
  259. ).body.conversation
  260. const rows = await req('get', '/api/app/conversations').expect(200)
  261. expect(rows.body.conversations).toHaveLength(3)
  262. await req('patch', `/api/app/conversations/${c.id}`)
  263. .send({ memberIds: [b.id], administratorId: b.id })
  264. .expect(400)
  265. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id] }).expect(200)
  266. expect((await req('get', `/api/app/conversations/${c.id}`)).body.conversation.memberIds).toEqual([a.id])
  267. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id, b.id] }).expect(200)
  268. await req('get', `/api/app/conversations/${c.id}`, 'second').expect(404)
  269. await req('patch', `/api/app/agents/${a.id}`, 'second').send({ name: '入侵' }).expect(404)
  270. expect((await req('get', '/api/app/events', 'second')).body.events).toEqual([])
  271. expect(upstream.some((p) => p.includes('sessions'))).toBe(false)
  272. })
  273. it('creates, lists, renames, selects, and deletes group tasks without changing remote members', async () => {
  274. const a = (
  275. await req('post', '/api/app/agents').send({ name: '本机管理员', profile: 'default' }).expect(201)
  276. ).body.agent
  277. const b = (
  278. await req('post', '/api/app/agents').send({ name: '远程成员', nodeId: 'local', profile: 'default' }).expect(201)
  279. ).body.agent
  280. const conversation = (
  281. await req('post', '/api/app/conversations')
  282. .send({ name: '多任务团队', memberIds: [a.id, b.id], administratorId: a.id })
  283. .expect(201)
  284. ).body.conversation
  285. const initial = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  286. expect(initial).toHaveLength(1)
  287. expect(initial[0]).toMatchObject({
  288. conversationId: conversation.id,
  289. title: '新任务',
  290. titleSource: 'automatic',
  291. messageCount: 0,
  292. })
  293. const task = (
  294. await req('post', `/api/app/conversations/${conversation.id}/tasks`)
  295. .send({ title: '远程 Agent 调研' })
  296. .expect(201)
  297. ).body.task
  298. expect(task).toMatchObject({ title: '远程 Agent 调研', titleSource: 'user' })
  299. const renamed = (
  300. await req('patch', `/api/app/conversations/${conversation.id}/tasks/${task.id}`)
  301. .send({ title: '远程 Agent 复核' })
  302. .expect(200)
  303. ).body.task
  304. expect(renamed).toMatchObject({ title: '远程 Agent 复核', titleSource: 'user' })
  305. const detail = (await req('get', `/api/app/conversations/${conversation.id}?taskId=${task.id}`).expect(200)).body
  306. expect(detail.task.id).toBe(task.id)
  307. expect(detail.tasks.map((row: { id: string }) => row.id)).toContain(task.id)
  308. expect(detail.messages).toEqual([])
  309. expect(detail.conversation).toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  310. expect((await req('put', `/api/app/conversations/${conversation.id}/tasks/${task.id}/read`).send({ seq: 100 }).expect(200)).body.task)
  311. .toMatchObject({ readSeq: 0, lastSeq: 0, unreadCount: 0 })
  312. await req('get', `/api/app/conversations/${conversation.id}/tasks`, 'second').expect(404)
  313. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${task.id}`).expect(200)
  314. const remaining = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  315. expect(remaining.map((row: { id: string }) => row.id)).not.toContain(task.id)
  316. expect((await req('get', `/api/app/conversations/${conversation.id}`)).body.conversation)
  317. .toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  318. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${initial[0].id}`).expect(200)
  319. const replacement = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  320. expect(replacement).toHaveLength(1)
  321. expect(replacement[0].id).not.toBe(initial[0].id)
  322. })
  323. it('archives files on the Web server, preserves native library fields, and blocks cross-user downloads', async () => {
  324. const f = (
  325. await req('post', '/api/app/uploads')
  326. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  327. .expect(201)
  328. ).body.files[0]
  329. expect(f.path).toBeUndefined()
  330. expect(runtime.uploads.cleanupUncommitted(0)).toBe(0)
  331. const list = await req('get', '/api/app/files').expect(200),
  332. item = list.body.items[0]
  333. expect(typeof item.id).toBe('number')
  334. expect(item.path).toBe(`/api/app/files/${f.id}/download`)
  335. expect(item).toMatchObject({ name: 'hello.txt', size: 5, exists: true, archiveStatus: 'ready' })
  336. expect((await req('get', item.path).expect(200)).text).toBe('hello')
  337. await req('get', item.path, 'second').expect(404)
  338. await req('get', `/api/app/files/${item.id}/download`, 'second').expect(404)
  339. expect((await req('get', '/api/app/files', 'second')).body.total).toBe(0)
  340. expect(upstream.some((p) => p.includes('/files'))).toBe(false)
  341. })
  342. it('does not serve uploaded HTML or SVG as executable same-origin previews', async () => {
  343. const f = (
  344. await req('post', '/api/app/uploads')
  345. .attach('files', Buffer.from('<svg onload="alert(1)"/>'), {
  346. filename: 'unsafe.svg',
  347. contentType: 'image/svg+xml',
  348. })
  349. .expect(201)
  350. ).body.files[0]
  351. const response = await req('get', `/api/app/files/${f.id}/preview`).expect(200)
  352. expect(response.headers['content-type']).toContain('application/octet-stream')
  353. expect(response.headers['content-disposition']).toContain('attachment')
  354. })
  355. it('persists encrypted voice credentials while giving each user their own selected voice', async () => {
  356. await req('put', '/api/app/admin/duplex-voice')
  357. .send({
  358. apiKey: 'private-test-key',
  359. voices: [
  360. { id: 'a', name: '甲' },
  361. { id: 'b', name: '乙' },
  362. ],
  363. currentVoiceId: 'a',
  364. })
  365. .expect(200)
  366. const publicResponse = await req('get', '/api/app/admin/duplex-voice').expect(200)
  367. expect(publicResponse.body.hasApiKey).toBe(true)
  368. expect(publicResponse.body.apiKey).toBeUndefined()
  369. await req('put', '/api/app/voice/current-voice', 'second')
  370. .send({ currentVoiceId: 'b' })
  371. .expect(200)
  372. expect((await req('get', '/api/app/voice/runtime')).body.currentVoiceId).toBe('a')
  373. expect((await req('get', '/api/app/voice/runtime', 'second')).body.currentVoiceId).toBe('b')
  374. expect(
  375. readFileSync(join(home, 'workspace.sqlite3')).includes(Buffer.from('private-test-key')),
  376. ).toBe(false)
  377. })
  378. it('stores monotonic profile-scoped context snapshots without a plugin', async () => {
  379. const path = '/api/app/session-context/session-one?profile=default'
  380. const b = { usedTokens: 200, limitTokens: 1000, percent: 20, observedAt: 20 }
  381. await req('put', path).send(b).expect(200)
  382. await req('put', path)
  383. .send({ ...b, usedTokens: 10, observedAt: 10 })
  384. .expect(200)
  385. expect((await req('get', path)).body.snapshot).toMatchObject({ ...b, sessionId: 'session-one' })
  386. expect((await req('get', path, 'second')).body.snapshot).toBeNull()
  387. expect(
  388. (await req('get', '/api/app/session-context/session-one?profile=other')).body.snapshot,
  389. ).toBeNull()
  390. })
  391. it('protects internal Hermes session IDs on native HTTP endpoints', async () => {
  392. runtime.workspace.put('first', 'binding', 'binding', {
  393. storedId: 'internal-session',
  394. runtimeId: 'internal-runtime',
  395. aliases: ['old-id'],
  396. })
  397. await req('get', '/api/app/sessions/internal-session/messages').expect(404)
  398. await req('get', '/api/sessions/old-id/messages', 'second').expect(404)
  399. expect(upstream.some((p) => p.includes('internal-session') || p.includes('old-id'))).toBe(false)
  400. })
  401. })