Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
a319424
feat(realtime): add shared room identity + authorization spine (#5929)
waleedlatif1 Jul 24, 2026
d4d2238
refactor(realtime): generalize presence server to multi-room [2/N] (#…
waleedlatif1 Jul 24, 2026
4a0f241
feat(files): live presence avatars + live file tree via realtime room…
waleedlatif1 Jul 24, 2026
a639af3
refactor(tables): adopt shared durable event-log core (#5934)
waleedlatif1 Jul 24, 2026
9a899d8
fix(realtime): address post-merge review-comment findings (#5937)
waleedlatif1 Jul 24, 2026
a1bb9f3
feat(realtime): Yjs relay server for collaborative document editing […
waleedlatif1 Jul 24, 2026
45cb10b
feat(files): collaborative document editing — client provider + edito…
waleedlatif1 Jul 25, 2026
790d93a
feat(tables): live collaboration — cell-selection presence + live mut…
waleedlatif1 Jul 25, 2026
0a36d64
feat(realtime): accurate in-file presence + collaborative-caret polis…
waleedlatif1 Jul 26, 2026
cddcb73
feat(files): smarter bullet delete/indent and untitled-file title syn…
mzxchandra Jul 27, 2026
120526f
Merge origin/staging into realtime-rooms
waleedlatif1 Jul 27, 2026
1f15cfc
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 27, 2026
bdf47c8
fix(realtime): access-revalidation multi-room safety + cleanup pass
waleedlatif1 Jul 27, 2026
aeda9b0
fix(realtime,tables): close table-presence race + v1/copilot live-col…
waleedlatif1 Jul 27, 2026
a7aa317
fix(tables): close two copilot live-collab signal gaps + harden prese…
waleedlatif1 Jul 27, 2026
3de7af1
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 27, 2026
869679f
fix(realtime): guard table join commit + rollback against supersessio…
waleedlatif1 Jul 28, 2026
0383d79
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
dee847b
fix(realtime): guard table join leave-prior against superseding join
waleedlatif1 Jul 28, 2026
ccfe294
fix(realtime): roll back a table join superseded during addUserToRoom
waleedlatif1 Jul 28, 2026
5cfa299
refactor(realtime): DRY table-join supersession guards; fix stale com…
waleedlatif1 Jul 28, 2026
2c40b3f
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
f09aa17
fix(realtime): file-doc rebind must not drop the current doc or leave…
waleedlatif1 Jul 28, 2026
2347dfc
refactor(realtime): serialize table join/leave to fix map-corruption …
waleedlatif1 Jul 28, 2026
43cfd6f
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
06cf68f
fix(realtime): always roll back a failed table join; re-elect file-do…
waleedlatif1 Jul 28, 2026
6ab59b9
fix(realtime): close revoke-race ghost presence in workflow join
waleedlatif1 Jul 28, 2026
59d7140
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
5c3b03c
refactor(realtime): serialize workflow join/leave; drop dead room-aut…
waleedlatif1 Jul 28, 2026
2bfb58e
fix(realtime): align session TTL, harden committed joins from post-su…
waleedlatif1 Jul 28, 2026
dfb6353
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
42d1d32
fix(realtime): narrow join commit-guard to post-success; skip empty p…
waleedlatif1 Jul 28, 2026
a694f75
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
8ae486a
fix(realtime): harden seeder recovery, join-generation, and misc robu…
waleedlatif1 Jul 28, 2026
19a5abd
fix(realtime): gate isReady() on loaded script SHAs, not just connection
waleedlatif1 Jul 28, 2026
7421628
fix(files): offline read-only fallback when the realtime doc never syncs
waleedlatif1 Jul 28, 2026
a58f928
fix(realtime): validate workflow join id before generation bump; scop…
waleedlatif1 Jul 28, 2026
2643970
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
f9f43c3
fix(files): drop late sync frames once fatal; file-doc join error sup…
waleedlatif1 Jul 28, 2026
06ecb6e
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
ba72663
feat(collab-doc): server-authoritative Yjs seeding (#6008)
waleedlatif1 Jul 28, 2026
66eef09
feat(collab-doc): Sim merge endpoint for copilot-into-doc (Stage C fo…
waleedlatif1 Jul 28, 2026
17f17e8
feat(collab-doc): realtime apply-edit — merge copilot markdown into a…
waleedlatif1 Jul 28, 2026
e43e9a1
feat(collab-doc): stream copilot edits into open editors (Stage C)
waleedlatif1 Jul 28, 2026
470b9d0
fix(collab-doc): strip frontmatter on merge; gate live-merge to markdown
waleedlatif1 Jul 28, 2026
a7a55c9
fix(collab-doc): make frontmatter collaborative so a merge can't reve…
waleedlatif1 Jul 28, 2026
43726ed
fix(collab-doc): re-sync draft on a frontmatter-only merge
waleedlatif1 Jul 28, 2026
6cf455b
fix(collab-doc): order the apply-edit/merge timeouts (outer > inner)
waleedlatif1 Jul 28, 2026
3c580f3
fix(collab-doc): address deep-audit findings (jsdom trace, timeouts, …
waleedlatif1 Jul 28, 2026
7844e9a
Merge remote-tracking branch 'origin/staging' into collab-doc-stage-c
waleedlatif1 Jul 28, 2026
499b6c0
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 28, 2026
0fd0e89
Merge remote-tracking branch 'origin/realtime-rooms' into collab-doc-…
waleedlatif1 Jul 28, 2026
c8ecfc0
feat(collab-doc): multi-replica shared Yjs backend + server-side mark…
waleedlatif1 Jul 29, 2026
5558be8
Merge pull request #6021 from simstudioai/collab-doc-stage-c
waleedlatif1 Jul 29, 2026
161b031
fix(collab-doc): harden distributed locks and durability from review
waleedlatif1 Jul 29, 2026
b528509
fix(collab-doc): only persist a doc a user actually edited
waleedlatif1 Jul 29, 2026
be2c9ad
fix(collab-doc): close review-round race/durability gaps
waleedlatif1 Jul 29, 2026
2f1933c
fix(collab-doc): unstick seed retry and persist tailed edits
waleedlatif1 Jul 29, 2026
9476b21
fix(collab-doc): match client markdown post-processing on server persist
waleedlatif1 Jul 29, 2026
f62e99f
fix(collab-doc): close durability gaps at deploy boundaries + audit p…
waleedlatif1 Jul 29, 2026
b9d2e67
Merge pull request #6036 from simstudioai/collab-doc-multireplica
waleedlatif1 Jul 29, 2026
320e18c
Merge remote-tracking branch 'origin/staging' into rt-rooms-sync
waleedlatif1 Jul 29, 2026
d3ca016
improvement(realtime): post-review fixes for collab dirty-state + rel…
waleedlatif1 Jul 29, 2026
7de77ea
Merge pull request #6043 from simstudioai/collab-review-fixes
waleedlatif1 Jul 29, 2026
ced03b3
fix(realtime): make collab-doc seeding atomic to close split-brain wi…
waleedlatif1 Jul 29, 2026
f83af6e
docs(realtime): align seed comments with the atomic-append correctnes…
waleedlatif1 Jul 29, 2026
079cf13
Merge pull request #6048 from simstudioai/collab-seed-atomic
waleedlatif1 Jul 29, 2026
c639d61
Merge origin/staging into realtime-rooms
waleedlatif1 Jul 29, 2026
4419951
feat(realtime): live workspace tables list, sharing one invalidation-…
waleedlatif1 Jul 29, 2026
2c88758
Merge origin/staging into realtime-rooms
waleedlatif1 Jul 29, 2026
11747bd
feat(collab-doc): Hocuspocus binary persistence + Next 16 seed/persis…
waleedlatif1 Jul 29, 2026
de595f4
Merge remote-tracking branch 'origin/staging' into realtime-rooms
waleedlatif1 Jul 29, 2026
fd34853
fix(collab-doc): stream every external file write into open editors, …
waleedlatif1 Jul 30, 2026
caa0a73
fix(rich-markdown-editor): defer non-collab settle/stream mutations o…
waleedlatif1 Jul 30, 2026
525c340
feat(tables): show live cell-selection carets in the embedded chat pa…
waleedlatif1 Jul 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/realtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@
"@sim/workflow-types": "workspace:*",
"@socket.io/redis-adapter": "8.3.0",
"drizzle-orm": "^0.45.2",
"lib0": "0.2.117",
"postgres": "^3.4.5",
"redis": "5.10.0",
"socket.io": "^4.8.1",
"y-protocols": "1.0.7",
"yjs": "13.6.31",
"zod": "4.3.6"
},
"devDependencies": {
Expand Down
76 changes: 50 additions & 26 deletions apps/realtime/src/access-revalidation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,14 @@ function makeManager(sockets: FakeSocket[], presence: Partial<UserPresence>[] =
const manager = {
io: { sockets: { sockets: socketMap } },
isReady: () => true,
getWorkflowUsers: vi.fn().mockResolvedValue(presence),
getWorkflowIdForSocket: vi.fn().mockResolvedValue(null),
removeUserFromRoom: vi
.fn()
.mockImplementation(async (_socketId: string, workflowId?: string) => workflowId ?? null),
getRoomUsers: vi.fn().mockResolvedValue(presence),
getRoomForSocket: vi.fn().mockResolvedValue(null),
removeUserFromRoom: vi.fn().mockResolvedValue(true),
broadcastPresenceUpdate: vi.fn().mockResolvedValue(undefined),
}
return manager as unknown as IRoomManager & {
getWorkflowUsers: ReturnType<typeof vi.fn>
getWorkflowIdForSocket: ReturnType<typeof vi.fn>
getRoomUsers: ReturnType<typeof vi.fn>
getRoomForSocket: ReturnType<typeof vi.fn>
removeUserFromRoom: ReturnType<typeof vi.fn>
broadcastPresenceUpdate: ReturnType<typeof vi.fn>
}
Expand All @@ -84,8 +82,11 @@ describe('access-revalidation sweep', () => {
expect.objectContaining({ workflowId: 'wf-1' })
)
expect(socket.leave).toHaveBeenCalledWith('wf-1')
expect(manager.removeUserFromRoom).toHaveBeenCalledWith('sock-1', 'wf-1')
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith('wf-1')
expect(manager.removeUserFromRoom).toHaveBeenCalledWith(
{ type: 'workflow', id: 'wf-1' },
'sock-1'
)
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith({ type: 'workflow', id: 'wf-1' })
})

it('keeps a socket whose access is still valid', async () => {
Expand Down Expand Up @@ -141,7 +142,30 @@ describe('access-revalidation sweep', () => {

expect(mockResolveRole).toHaveBeenCalledWith('user-1', 'wf-1', 'read')
// The security scan must stay Redis-free — presence is never consulted.
expect(manager.getWorkflowUsers).not.toHaveBeenCalled()
expect(manager.getRoomUsers).not.toHaveBeenCalled()
})

it('never evicts a socket joined only to a non-workflow room (files/tables/file-doc)', async () => {
// The sweep shares one io with the files/tables/file-doc handlers. Those rooms are
// namespaced (`workspace-files:ws-1`, `table:t-1`), so treating every socket.rooms
// entry as a workflow id would resolve a bogus permission → null → evict the socket
// from its files/table room every pass. Non-workflow rooms must be filtered out.
const filesSocket = makeSocket('sock-1', 'user-1', 'workspace-files:ws-1')
const tableSocket = makeSocket('sock-2', 'user-2', 'table:t-1')
const manager = makeManager([filesSocket, tableSocket])
// Even if the role resolver would say "no access", these must never be swept.
mockResolveRole.mockResolvedValue(null)

const sweep = startAccessRevalidationSweep(manager)
await sweep.runOnce()
sweep.stop()

expect(mockResolveRole).not.toHaveBeenCalled()
expect(filesSocket.leave).not.toHaveBeenCalled()
expect(filesSocket.emit).not.toHaveBeenCalled()
expect(tableSocket.leave).not.toHaveBeenCalled()
expect(tableSocket.emit).not.toHaveBeenCalled()
expect(manager.removeUserFromRoom).not.toHaveBeenCalled()
})

it('evicts only the revoked socket, not co-members of the room', async () => {
Expand Down Expand Up @@ -199,37 +223,37 @@ describe('access-revalidation sweep', () => {
sweep.stop()

expect(manager.removeUserFromRoom).toHaveBeenCalledTimes(2)
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith('wf-1')
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith({ type: 'workflow', id: 'wf-1' })
})

it('defers cleanup when removal fails with expired socket mappings', async () => {
it('drops eviction cleanup when the socket is no longer mapped to the room (no infinite retry)', async () => {
const socket = makeSocket('sock-1', 'user-1', 'wf-1')
const manager = makeManager([socket], [{ socketId: 'sock-1', role: 'read' }])
// Mapping keys already expired (lookup resolves null) AND the removal fails
// (the Redis manager swallows the transport error into null) — the failed
// removal must still defer instead of reading as success.
manager.removeUserFromRoom.mockResolvedValueOnce(null)
// A healthy lookup shows the socket is no longer mapped to any workflow room (its presence
// is already gone), and removeUserFromRoom reports a no-op `false`. This is "already clean",
// not a deferrable failure — the cleanup must drop it, never re-enqueue a still-connected
// socket forever. (A genuine failure — still mapped + false — is covered by the next test.)
manager.getRoomForSocket.mockResolvedValue(null)
manager.removeUserFromRoom.mockResolvedValue(false)
mockResolveRole.mockResolvedValue(null)

const sweep = startAccessRevalidationSweep(manager)
await sweep.runOnce()

expect(manager.broadcastPresenceUpdate).not.toHaveBeenCalled()

await sweep.runOnce()
sweep.stop()

expect(manager.removeUserFromRoom).toHaveBeenCalledTimes(2)
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith('wf-1')
// Attempted once, then dropped — not re-enqueued across passes, and no broadcast.
expect(manager.removeUserFromRoom).toHaveBeenCalledTimes(1)
expect(manager.broadcastPresenceUpdate).not.toHaveBeenCalled()
})

it('defers cleanup when the manager swallows a removal failure into null', async () => {
const socket = makeSocket('sock-1', 'user-1', 'wf-1')
const manager = makeManager([socket], [{ socketId: 'sock-1', role: 'read' }])
// Live mapping but the removal reports nothing removed — the Redis manager
// swallows transport errors into null, so this is the only failure signal.
manager.getWorkflowIdForSocket.mockResolvedValue('wf-1')
manager.removeUserFromRoom.mockResolvedValueOnce(null)
manager.getRoomForSocket.mockResolvedValue({ type: 'workflow', id: 'wf-1' })
manager.removeUserFromRoom.mockResolvedValueOnce(false)
mockResolveRole.mockResolvedValue(null)

const sweep = startAccessRevalidationSweep(manager)
Expand All @@ -243,15 +267,15 @@ describe('access-revalidation sweep', () => {
sweep.stop()

expect(manager.removeUserFromRoom).toHaveBeenCalledTimes(2)
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith('wf-1')
expect(manager.broadcastPresenceUpdate).toHaveBeenCalledWith({ type: 'workflow', id: 'wf-1' })
})

it('skips removal when the socket has since moved to a different workflow', async () => {
const socket = makeSocket('sock-1', 'user-1', 'wf-1')
const manager = makeManager([socket], [{ socketId: 'sock-1', role: 'read' }])
// Between the membership snapshot and cleanup, the socket switched to a
// workflow it can still access — removal must not touch its new presence.
manager.getWorkflowIdForSocket.mockResolvedValue('wf-2')
manager.getRoomForSocket.mockResolvedValue({ type: 'workflow', id: 'wf-2' })
mockResolveRole.mockResolvedValue(null)

const sweep = startAccessRevalidationSweep(manager)
Expand Down Expand Up @@ -357,7 +381,7 @@ describe('access-revalidation sweep', () => {
const manager = makeManager([socket], [{ socketId: 'sock-1', role: 'read' }])
// A Redis outage where commands hang in the offline queue instead of
// failing: the cleanup lane stalls, but scans must keep running.
manager.getWorkflowIdForSocket.mockReturnValue(new Promise(() => {}))
manager.getRoomForSocket.mockReturnValue(new Promise(() => {}))
mockResolveRole.mockResolvedValue(null)

const sweep = startAccessRevalidationSweep(manager)
Expand Down
57 changes: 43 additions & 14 deletions apps/realtime/src/access-revalidation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { createLogger } from '@sim/logger'
import type { AccessRevokedBroadcast } from '@sim/realtime-protocol/events'
import { parseRoomName, ROOM_TYPES } from '@sim/realtime-protocol/rooms'
import { sleep } from '@sim/utils/helpers'
import type { AuthenticatedSocket } from '@/middleware/auth'
import { ROLE_REVALIDATION_TTL_MS, resolveCurrentWorkflowRole } from '@/middleware/permissions'
import type { IRoomManager } from '@/rooms'
import { type IRoomManager, workflowRoom as wf } from '@/rooms'

const logger = createLogger('AccessRevalidation')

Expand Down Expand Up @@ -65,9 +66,14 @@ interface ScanTarget {
* Collects this pod's authenticated sockets with the workflow room each has
* joined, in stable socket order.
*
* The workflow room is derived from the socket's own `rooms` set (pod-local, no
* Redis round-trips): a socket joins exactly one workflow room, so its rooms are
* `{ ownSocketId, workflowId }`. Only local sockets are evaluated — sockets are
* Rooms are derived from the socket's own `rooms` set (pod-local, no Redis
* round-trips). A socket may occupy several rooms of different types at once
* (workflow canvas, workspace-files browser, table, file-doc), all on the same
* io — so each name is decoded with {@link parseRoomName} and only **workflow**
* rooms are swept here. Non-workflow room names are namespaced (`type:id`) and
* resolve to a non-workflow type; sweeping them as workflow ids would resolve a
* bogus permission, come back `null`, and spuriously evict the socket from its
* files/table room every pass. Only local sockets are evaluated — sockets are
* sticky to a pod, so every socket is swept by exactly one pod using that pod's
* warm role cache (mirroring the per-pod reasoning of the write-path cache).
*/
Expand All @@ -78,7 +84,9 @@ function collectScanTargets(io: IRoomManager['io']): ScanTarget[] {
if (!authed.userId) continue
for (const room of socket.rooms) {
if (room === socket.id) continue
targets.push({ workflowId: room, socket: authed, userId: authed.userId })
const ref = parseRoomName(room)
if (ref?.type !== ROOM_TYPES.WORKFLOW) continue
targets.push({ workflowId: ref.id, socket: authed, userId: authed.userId })
}
}
return targets
Expand Down Expand Up @@ -129,9 +137,20 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR
async function cleanupEvictedSocket(socketId: string, workflowId: string): Promise<void> {
const key = `${socketId}:${workflowId}`
try {
// A fully-disconnected socket already had its presence removed by the
// disconnect handler (removeSocketFromAllRooms), so there is nothing left to
// clean. Dropping here also keeps the boolean removeUserFromRoom below from
// reporting a false "not a member" for an already-gone entry and retrying it
// forever (the pre-generalization manager returned the target on a no-op).
if (!io.sockets.sockets.get(socketId)) {
pendingCleanups.delete(key)
return
}

// Unlike removeUserFromRoom, this read does not swallow transport errors,
// so a Redis outage lands in the catch below and defers the cleanup.
const currentWorkflowId = await roomManager.getWorkflowIdForSocket(socketId)
const currentRoom = await roomManager.getRoomForSocket(socketId, ROOM_TYPES.WORKFLOW)
const currentWorkflowId = currentRoom?.id ?? null
if (currentWorkflowId !== null && currentWorkflowId !== workflowId) {
// The socket has since moved to a different workflow it can still
// access; that join's room switch already removed this room's presence
Expand All @@ -148,16 +167,26 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR
return
}

const removed = await roomManager.removeUserFromRoom(socketId, workflowId)
if (removed === null) {
// The sweep always passes the target room, and both managers report a
// performed removal by returning it — the Redis manager swallows
// transport errors into null, so null means the removal did not happen
// (even when the socket's mapping keys have already expired).
throw new Error('room-state removal not confirmed')
// A null mapping here is the normal case (the socket's mapping key may have
// expired) and does NOT mean "skip" — the eviction still removes the presence
// entry from the known target room via the explicit ref below.
const removed = await roomManager.removeUserFromRoom(wf(workflowId), socketId)
if (!removed) {
// `false` conflates two outcomes: the entry was already gone (a no-op), or a
// transport error the manager swallowed. Only retry when the socket is still mapped
// to THIS room — then a false result is a genuine, deferrable failure. When a healthy
// getRoomForSocket above returned no workflow mapping (`currentWorkflowId === null`),
// the presence entry is already gone, so the cleanup is complete: dropping it avoids
// re-enqueuing a still-connected socket forever. (A real Redis outage throws at
// getRoomForSocket and is deferred by the outer catch, never reaching here.)
if (currentWorkflowId === workflowId) {
throw new Error('room-state removal not confirmed')
}
pendingCleanups.delete(key)
return
Comment thread
cursor[bot] marked this conversation as resolved.
}

await roomManager.broadcastPresenceUpdate(workflowId)
await roomManager.broadcastPresenceUpdate(wf(workflowId))
pendingCleanups.delete(key)
} catch (error) {
pendingCleanups.set(key, { socketId, workflowId })
Expand Down
29 changes: 29 additions & 0 deletions apps/realtime/src/handlers/avatar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { db, user } from '@sim/db'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import type { AuthenticatedSocket } from '@/middleware/auth'

const logger = createLogger('PresenceAvatar')

/**
* The avatar URL for a presence entry: the socket's authenticated image when
* present, otherwise a single lookup of the user's stored image. Never throws —
* presence must not fail on an avatar lookup, so a DB error resolves to `null`.
*/
export async function resolveAvatarUrl(
socket: AuthenticatedSocket,
userId: string
): Promise<string | null> {
if (socket.userImage) return socket.userImage
try {
const [record] = await db
.select({ image: user.image })
.from(user)
.where(eq(user.id, userId))
.limit(1)
return record?.image ?? null
} catch (error) {
logger.warn('Failed to load user avatar for presence', { userId, error })
return null
}
}
Loading
Loading