Open History to see the last commit
1---
2title: Share a thread between people
3id: harness-shared-threads
4order: 7
5description: "Let a team use one thread. Share it with members and viewers, and run each message as its sender, with the credentials and the provider key of that person."
6keywords:
7 - tanstack ai
8 - harness
9 - shared thread
10 - membersOnly
11 - share
12 - tenantId
13 - canJoin
14---
15
16Several people work in one thread: a team in one chat, or a customer and a support agent. Only the people you invite can see it. A message from Bob must run as Bob: his GitHub token and his provider key do the work, not those of the person who opened the thread. `membersOnly()` gives each thread an owner and a list of members, and the harness runs each message as the person who sent it.
17
18## 1. Turn on members
19
20Use `membersOnly()` as the `rules` of the host `access`. [Access and tenants](./access) explains `getUser`:
21
22```ts group=harness-shared-threads
23import { createHarnessHost, defineHarness, membersOnly } from '@tanstack/ai-harness'
24import { createHarnessHandler } from '@tanstack/ai-harness/server'
25import { memoryPersistence } from '@tanstack/ai-persistence'
26import { openaiText } from '@tanstack/ai-openai'
27
28export const assistant = defineHarness({
29 name: 'acme/assistant',
30 adapter: openaiText('gpt-6.1-sol'),
31})
32
33// Your own login check: a session token to a user.
34const users = new Map([
35 ['Bearer token-ada', { id: 'ada', tenantId: 'acme' }],
36 ['Bearer token-bob', { id: 'bob', tenantId: 'acme' }],
37])
38
39export const host = createHarnessHost({
40 persistence: memoryPersistence(),
41 access: {
42 getUser: ({ request }) => users.get(request.headers.get('authorization') ?? '') ?? null,
43 rules: membersOnly(),
44 },
45})
46
47export const handler = createHarnessHandler({ host, harness: assistant })
48```
49
50The user who opens a new thread is its owner. Nobody else can open it until the owner shares it. What each role can do:
51
52| Action | Owner | Member | Operator | Viewer |
53| --- | --- | --- | --- | --- |
54| Read the thread and see it in a list | Yes | Yes | Yes | Yes |
55| Send messages, run commands, start agents | Yes | Yes | No | No |
56| Answer and cancel | Every run | Only the runs they started | No | No |
57| Answer a `human` wait, and reply as an [operator](./handoffs#reply-as-the-operator) | No | No | Yes | No |
58| Fork | Yes | Yes | No | No |
59| Configure, share, delete, erase, transfer | Yes | No | No | No |
60
61The user who waits for a person must not act as that person, so the owner does not get `operator`. To give it to other roles, pass `membersOnly({ operator: { roles: ['owner', 'operator'] } })`.
62
63A user who is not a member can do nothing. A child thread of a subagent uses the members of its root thread.
64
65## 2. Share the thread
66
67The owner adds a member from your server code:
68
69```ts group=harness-shared-threads
70const ada = { id: 'ada', tenantId: 'acme' }
71
72await host.open(assistant, { threadId: 'team-thread', user: ada })
73await host.sessions.share({
74 threadId: 'team-thread',
75 userId: 'bob',
76 role: 'member',
77 user: ada,
78})
79```
80
81From the browser, the owner calls `client.sessions.share`:
82
83```ts group=harness-shared-threads-invite
84import { createHarnessClient } from '@tanstack/ai-harness/client'
85import type { assistant } from './harness'
86
87const client = createHarnessClient<typeof assistant>({
88 url: '/api/harness',
89 threadId: 'team-thread',
90 headers: { authorization: 'Bearer token-ada' },
91})
92
93const entry = await client.sessions.share({ threadId: 'team-thread', userId: 'bob', role: 'member' })
94console.log(entry.members) // [{ userId: 'ada', role: 'owner' }, { userId: 'bob', role: 'member' }]
95
96await client.sessions.unshare({ threadId: 'team-thread', userId: 'bob' })
97```
98
99- `share` adds a member, or changes the role of a member. It resolves to the changed entry.
100- `unshare` removes a member: `host.sessions.unshare({ threadId, userId, user })` on the server, or `client.sessions.unshare({ threadId, userId })` from the browser. It resolves to the changed entry.
101- Only the owner can share. Another user gets `AccessDeniedError`, and the handler answers `403`.
102- The owner cannot be removed.
103
104When `unshare` removes a user:
105
106- The queued and running work that the user started stops, on every host. The log keeps who cancelled it. The schedules of the user on the thread are removed.
107- The streams of the user on the thread close. A socket gets a `forbidden` error frame. A running `events()` read of a handle or a view ends with `AccessDeniedError`.
108- The open handles and views of the user throw `AccessDeniedError`.
109- The signed media URLs of the user stop working.
110
111## 3. Connect each person
112
113Each person opens the same thread with their own token. This snippet shows two clients. In a real app, each person has one client in their own browser:
114
115```ts group=harness-shared-threads-client
116import { createHarnessClient } from '@tanstack/ai-harness/client'
117import type { assistant } from './harness'
118
119const ada = createHarnessClient<typeof assistant>({
120 url: '/api/harness',
121 threadId: 'team-thread',
122 headers: { authorization: 'Bearer token-ada' },
123})
124const bob = createHarnessClient<typeof assistant>({
125 url: '/api/harness',
126 threadId: 'team-thread',
127 headers: { authorization: 'Bearer token-bob' },
128})
129
130await ada.send('Open an issue for the login bug.')
131await bob.send('List my open pull requests.')
132```
133
134Bob sends his message while the turn of Ada runs. His message waits. Then it runs as its own turn, as Bob.
135
136On the server, open one handle for each person. A handle acts only as its user:
137
138```ts group=harness-shared-threads
139const bob = { id: 'bob', tenantId: 'acme' }
140const bobSession = await host.open(assistant, { threadId: 'team-thread', user: bob })
141
142await bobSession.send('Summarize the open issues.')
143```
144
145## 4. Each message runs as its sender
146
147Each message, command, and agent runs as the person who started it:
148
149- The log keeps the sender of each input, also of a cancel, an answer, and a change of settings. After a restart, a message runs again as its sender. An input with no sender runs with no user, so it does not use the credentials of the session that owns the thread. A host with access refuses that input.
150- Tools and middleware read the run as `ctx.context.run`. It has the user, the credentials, and the provider keys of the sender.
151- The model call uses the provider key of the sender. So the sender pays for the call.
152- An answer does not change the sender. When the owner approves a tool in the turn of Bob, the rest of that turn still runs as Bob.
153- A command runs as the person who runs it. So a sign-in, for example `connect:github`, belongs to the person who signed in.
154- A background agent runs as the person who started it, also after the turn ends. The wake turn after the agent runs as that person too.
155
156A tool reads the credentials of the user of its own run:
157
158```ts group=harness-shared-threads
159import { toolDefinition } from '@tanstack/ai'
160import type { HarnessRunContext } from '@tanstack/ai-harness'
161
162export const myIssues = toolDefinition({
163 name: 'my_linear_issues',
164 description: 'List the Linear issues of the user',
165}).server<HarnessRunContext>(async (_args, ctx) => {
166 const credential = await ctx.context.run.credentials.require('linear')
167 const key = credential.type === 'oauth' ? credential.accessToken : credential.value
168 const response = await fetch('https://api.linear.app/graphql', {
169 method: 'POST',
170 headers: { authorization: key, 'content-type': 'application/json' },
171 body: JSON.stringify({ query: '{ viewer { assignedIssues { nodes { title } } } }' }),
172 })
173 return response.json()
174})
175```
176
177A command that saves a sign-in or a key saves it with the `credentials` of its run context. Those credentials belong to the person who runs the command:
178
179```ts group=harness-shared-threads
180import { defineCommand, definePlugin } from '@tanstack/ai-harness'
181import { z } from 'zod'
182
183export const linearKey = definePlugin({
184 name: 'acme/linear-key',
185 setup: () => ({
186 commands: {
187 'connect:linear': defineCommand({
188 description: 'Save a Linear API key',
189 input: z.object({ key: z.string() }),
190 run: async ({ key }, { credentials }) => {
191 await credentials.set({
192 id: 'linear',
193 credential: { type: 'api_key', value: key },
194 })
195 return 'Connected to Linear.'
196 },
197 }),
198 },
199 }),
200})
201```
202
203The `ctx.credentials` of a plugin `setup` have no user, so each call throws. See [Act as the user of a run](./plugins#act-as-the-user-of-a-run).
204
205Context that a client sends with a message is client data, and it never changes the sender. See [Send context with a message](./inputs#send-context-with-a-message).
206
207## 5. Keep other people out of a running turn
208
209A message with `busy: 'steer'` can join the turn that runs now. A joined message runs with the credentials of the sender of that turn. So without `turn.canJoin`, a waiting message joins the running turn only when the same person sent both:
210
211- A message from another person waits. It runs as its own turn after the running one, as its sender.
212- The waiting messages join as a prefix, in the order they arrived. So a message that waits also holds back the messages that wait after it.
213
214Set `canJoin` to choose your own rule. It gets the sender of the waiting message as `user`, and the sender of the running turn as `turnUser`. This harness keeps the default rule, and it also lets your build bot join any turn:
215
216```ts group=harness-shared-threads
217export const team = defineHarness({
218 name: 'acme/team',
219 adapter: openaiText('gpt-6.1-sol'),
220 turn: {
221 canJoin: ({ user, turnUser }) =>
222 user?.id === 'build-bot' ||
223 (user?.id === turnUser?.id &&
224 user?.tenantId === turnUser?.tenantId),
225 },
226})
227```
228
229## 6. Fork a shared thread
230
231Bob wants to try another path without changing the thread of the team. He forks it. The user who forks owns the fork:
232
233```ts group=harness-shared-threads
234const [first] = await bobSession.transcript()
235if (!first?.id) throw new Error('The thread has no messages.')
236
237const fork = await host.sessions.fork({
238 harness: assistant,
239 threadId: 'team-thread',
240 at: { through: first.id },
241 members: 'all',
242 user: bob,
243})
244console.log(fork.members[0]) // { userId: 'bob', role: 'owner' }
245```
246
247`members` picks who else is in the fork:
248
249- `'self'`: only the user who forks.
250- `'all'`: the members of the old thread keep their roles. The old owner becomes a `member`.
251
252Without `members`, the fork uses `fork.members` of `membersOnly()`, and the default is `'self'`. To change it for every fork, pass `membersOnly({ fork: { members: 'all' } })`.
253
254## 7. Keep organizations apart
255
256The tenant of a user picks the thread. One `threadId` in two tenants is two threads, so Acme and Globex never see each other's work. See [Keep tenants apart](./access#keep-tenants-apart).
257
258The credential scope of a run has the `userId` and the `tenantId` of its user. So one person in two organizations has two sets of credentials. The memory store of `memoryPersistence()` keeps them apart. In your own credential store, put `scope.tenantId` in the key:
259
260```ts group=harness-shared-threads
261import type { Scope } from '@tanstack/ai'
262
263export const keyOf = (scope: Scope, id: string) =>
264 `${scope.tenantId ?? '-'}:${scope.userId ?? '-'}:${id}`
265```
266
267Use `keyOf` in `get`, `set`, `delete`, and `list` of the store in [Keep credentials](./auth#keep-credentials).
268
269### Share one credential with the whole organization
270
271Some services have one key for the whole organization, for example a company account. Save that key once, with no `userId`. Every user of the tenant can then use it:
272
273```ts group=harness-shared-threads
274import type { CredentialStore } from '@tanstack/ai/byok'
275
276// Your admin code. A credential without a userId belongs to the tenant.
277export async function shareKey(
278 store: CredentialStore,
279 tenantId: string,
280 value: string,
281) {
282 await store.set({
283 scope: { tenantId },
284 id: 'linear',
285 credential: { type: 'api_key', value },
286 })
287}
288```
289
290- A run reads the credential of its user first. If the user has none, the run reads the credential of the tenant.
291- A save from a run goes to its user only. This includes `connect:<id>` and `run.credentials.set`. The credential of the tenant does not change.
292- `run.credentials.list()` shows the credentials of the user and of the tenant. For the same id, the credential of the user wins.
293- An OAuth token of the tenant works too. A refresh saves the new token for the tenant, so every user of the tenant gets it. See [Refresh a token](./auth#refresh-a-token).
294
295## 8. Show who is here
296
297Ada and Bob work in one thread. Each of them wants to see who else has the thread open now. The `presence` hooks of the host tell you when a client stream starts and when it ends.
298
299On the server, keep the open streams of each thread, and serve the list:
300
301```ts group=harness-shared-threads
302// The open streams on this server: thread id, then connection id, then user id.
303const online = new Map<string, Map<string, string>>()
304
305export const presenceHost = createHarnessHost({
306 persistence: memoryPersistence(),
307 access: {
308 getUser: ({ request }) => users.get(request.headers.get('authorization') ?? '') ?? null,
309 rules: membersOnly(),
310 },
311 presence: {
312 onConnect: ({ threadId, connectionId, user }) => {
313 const streams = online.get(threadId) ?? new Map<string, string>()
314 streams.set(connectionId, user?.id ?? 'guest')
315 online.set(threadId, streams)
316 },
317 onDisconnect: ({ threadId, connectionId }) => {
318 online.get(threadId)?.delete(connectionId)
319 },
320 },
321})
322
323// GET /api/who?threadId=team-thread: the users who have the thread open.
324export async function whoIsHere(request: Request) {
325 const user = users.get(request.headers.get('authorization') ?? '')
326 const threadId = new URL(request.url).searchParams.get('threadId') ?? ''
327 // Only a user who can read the thread sees the list. Another user gets AccessDeniedError.
328 const entry = user && (await presenceHost.sessions.get({ threadId, user }))
329 if (!entry) return new Response('Not found', { status: 404 })
330 return Response.json([...new Set(online.get(threadId)?.values())])
331}
332```
333
334In the browser, show the list:
335
336```ts group=harness-shared-threads-presence-client
337export async function showWhoIsHere(list: HTMLElement) {
338 const response = await fetch('/api/who?threadId=team-thread', {
339 headers: { authorization: 'Bearer token-ada' },
340 })
341 if (!response.ok) return
342 const userIds: unknown = await response.json()
343 if (Array.isArray(userIds)) list.textContent = `Here now: ${userIds.join(', ')}`
344}
345```
346
347Call `showWhoIsHere` when the page opens. To update it at once, publish a change from the hooks with your own pub/sub, and call it again when the change comes.
348
349- Each stream is one connection with its own `connectionId`. Two tabs of Bob are two connections, so the route counts users, not streams.
350- `GET events` and the socket of `handleHarnessSocket` count. `POST run` streams and reads from your own code do not.
351- `resumed` is `true` for a stream that goes on from a cursor, for example a reconnect.
352- `onDisconnect` runs once for each `onConnect`. Its `reason` is `closed`, `revoked` (a revoke or `unshare`), or `error`. `error` includes a stream that the server closes because the client reads too slowly.
353- Each server reports only its own streams. When more than one server runs, keep the streams in a shared store, for example Redis, in place of the `Map`.
354
355The host does not wait for a hook. A hook that throws or rejects only logs a warning, and the stream goes on.
356
357## 9. Erase the messages of one person
358
359Bob leaves the team and asks you to remove what he wrote. Take him out of the thread, then erase his messages. The thread stays for the others:
360
361```ts group=harness-shared-threads
362await host.sessions.unshare({ threadId: 'team-thread', userId: 'bob', user: ada })
363await host.sessions.eraseUser({
364 harness: assistant,
365 threadId: 'team-thread',
366 userId: 'bob',
367 user: ada,
368})
369```
370
371- Each message of Bob keeps its id and its role, and its content becomes `[removed]`. The turns keep their shape, so the model can go on.
372- The media files that Bob sent in those messages are deleted.
373- A [compaction](./compaction) summary can quote Bob, so the model context drops it and gets the whole transcript again. The next turn compacts again when it needs to.
374- `replies: 'remove'` also erases the answers to each message of Bob, up to the next user message. Default: `'keep'`.
375- The host writes a new [snapshot](./durable-sessions#keep-a-long-log-fast-to-open) without that content. Then the log drops every record before it. A reader whose cursor is before the snapshot gets one `harness.gap` event.
376- On a host with `access`, `eraseUser` needs the `erase` action. With `membersOnly()`, only the owner has it.
377
378`eraseUser` throws while a turn runs or waits on the thread, or while another host runs it. Wait until the thread is idle, then call it again.
379
380CAUTION: `eraseUser` changes only the messages. Your own records in the log, the plugin state, and the session title can still hold text of Bob. Remove that data in your own code.
381
382## What you have now
383
384- Threads that only their members can see, with an owner, members, and viewers.
385- Each message runs as the person who sent it, also after a restart.
386- Tools and model calls use the credentials and the provider key of the sender.
387- A message from another person waits for its own turn.
388- Forks that the forker owns, with the members you pick.
389- The threads and credentials of two organizations stay apart.
390- An erase that removes the messages of one person and keeps the thread.
391- A list of who has the thread open now.