Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

24.3 KB
Raw Blame

Channel persistence boundary

Channel owns a public collaboration timeline and triggers existing Agent conversations. This package provides the data contract; it does not activate Channel routers, runtime adapters, subscriptions or a details UI. Repository transactions lock the channels row before coordinating public messages, deliveries, topics and operations.

Storage

Responsibility Storage
Membership, roles, routing, branches, ordering Channel tables
Conversation kind channels.agentId: bound Agent for a direct conversation; NULL for a group
Message sender channel_messages.userId or agentId; never the requesting user on an Agent message
Public content and replies channel_messages.content; independent IDs
Public attachments channel_message_files, with sender-checked file references and order
Internal conversation Ordinary topics and messages, with the actual Agent and requester
CLI resume handle Topic metadata.heteroSessionId (not a database topic ID)
Execution status, errors, usage, traces One ordinary agent_operations row per claimed job
Source relation and coordination channel_jobs.topicId / operationId, input window, FIFO, lease, locks, publication

There is no channel_id on ordinary messages, topics or operations, no public Channel topic, and no separate Channel session/run/runtime-message store. trigger='channel' records the origin of an ordinary conversation/execution. The job points to it from the source side.

A direct conversation binds channels.userId (its human participant) and channels.agentId. ChannelRepository.create({ agentId, title }) checks Agent access, creates both members atomically, and requires private visibility. It opens the default conversation: a unique index on Agent, person and scope keeps one per pair, so repeated or concurrent calls return the existing channel. The scope is part of the key because a transferred Agent starts a new conversation in its new workspace. Only that human participant can access it, even if another membership is accidentally granted. It accepts no additional Agent members and routes unmentioned messages directly to the bound Agent. Group channels leave agentId NULL, including groups with only one Agent. A group whose only active members are one person and one Agent also skips routing: every message that mentions no Agent, in the main timeline or any Thread, goes to that Agent, which then follows the Thread. Deleting a bound Agent cascades its direct conversations and their public history. While Channels are on, creating an Agent opens its creator's conversation, titled with the Agent's name, with the Agent on the device and directory a new Channel would give it (createAgentDirectChannel). A project's default Channel (createDefaultChannel, titled General) carries metadata.projectDefault. Every Channel the router hands a client gets displayTitle (withDisplayTitles): the project's name for that marked Channel while the project is live and named, else title. It is read each time, so a project rename shows at once, and renaming the Channel edits only title, keeping the mark. Inviting from a direct conversation leaves it as it is and starts a group instead (createGroupFromDirect): its person and Agent, the Agent in the same channel-local environment, plus the invited Agents and people. userCandidates lists those people from a direct conversation; addUser still refuses it. People a group takes are those its inviter can talk with one-on-one: in a workspace, its members; in the personal space, the inviter's mutual contacts.

Group history survives deletion of an author or Agent. Message sender references use SET NULL; new writes require exactly one actual sender. Human requests have userId, Agent replies have agentId; the database forbids mixing these roles. Both references can be NULL only in retained history through repository writes. The existing routingStatus='reply' identifies Agent replies after deletion; other statuses are human requests. Context authors expose the actual user/Agent ID (or NULL after deletion) and resolve names from those entities, with deleted-author fallbacks. Member IDs still identify mentions, Thread followers, requester permissions and execution environments. The claimed manifest freezes the replying Agent ID so rebinding a member cannot change authorship.

Member, grant, message and job IDs are database-generated UUIDs; message references use UUID columns as well. Agent members reference agents.id; deletion clears that reference and blocks new claims, retaining group history. Optional channels.project_id is cleared on project deletion. Project association does not grant Channel access. Personal channels and direct conversations, including workspace ones, are removed with their owner; workspace groups retain their public history if the creator leaves or deletes their account.

ChannelRepository.addAgent requires an admin and a usable Agent in the current scope. The nullable reference exists for deletion history, not for creating an unbound Agent member. The member's config contains only the Channel device, device owner and working directory. Its name and description are Channel routing/execution labels; message author names come from the actual sender.

In a workspace Channel, an Agent member may run on a device that is not shared with the workspace only under a channel_member_grants row for exactly its device, owner and directory (grants.ts). Writing the environment (addAgent, updateAgentEnvironment) keeps the row in step: the device owner picking their own device approves it at once; anyone else's pick (only the Agent owner's private devices are offered to them) waits as pending. Saving the same environment keeps the decision; any other environment replaces it. A claim that finds no row (the device was made private after it was picked) files a pending request for the waiting requester. The device owner lists requests with listDeviceGrants and approves, rejects or revokes with decideDeviceGrant, which refuses a grant whose environment has since moved. The server also asks them as the Agent (announceDeviceGrants in the channel services): a card in their direct conversation with it, metadata.deviceGrant under request key device-grant:<grantId>. The view adds the grant's live status for the device owner, expired once the grant is gone.

Every claim rechecks the actual requester's Agent access and reads the Agent's current settings. Configuration uses the same merge function as AgentService: system defaults, server defaults, personal defaults (personal scope only), then the Agent. Workers must supply trusted getServerDefaultAgentConfig() output in serverDefaultAgentConfig ({} when unconfigured). The job's executionConfig freezes those settings, the Agent runtime and the Channel environment. Updating Agent settings affects the next claim, including already queued requests; it never rewrites an earlier job snapshot. A private, trashed, deleted or moved Agent fails the requester access check before any topic or operation is created.

Shared Agents

A personal direct conversation can also bind another person's Agent through its live link share. A link share is open to anyone signed in, so neither friendship nor a contact entry is needed: ChannelService.openShared opens the conversation from the share id, handle or pasted link, and createSharedDirect from an Agent the person added to their contacts (which shows they reached the share). Only those paths pass sharedAgent to create; a bare Agent id never binds someone else's Agent. requireChannelAgent and resolveExecutionConfig then accept it for that conversation shape only, while the share is link and the Agent is not trashed; groups and workspace channels never take one. The claim freezes executionConfig.share (owner, share and the Agent's scope):

  • The run executes as the owner, like a visit to the share page. Its topic and operation belong to the owner and the Agent's scope, with the requester as topics.senderId, so the owner's own lists never show it. Owner defaults apply; the requester's never do.
  • It is always a Native cloud run: no device, no Channel project, no attachments (sending refuses them because the owner's run cannot read the requester's files).
  • The coordinator rechecks the live share and its monthly spend limit before submission and runs under the share's shareGate. Of the Channel tools it keeps only readMessages / readMessage, and ChannelHistoryRepository authorizes those reads against the frozen share (owner operation, the person's Channel) while every other use of the run (currentRun, so listChannels / sendMessage) is refused: they would act in the owner's Channels.
  • Each requester can send at most the share's maxMessagesPerVisitor messages in total, counted across all their topics with this Agent; sending refuses the next one. Topics still roll over only after the staleness window.

Conversations between contacts

channels.peerUserId marks a one-on-one conversation between two people (openPeer). One exists per pair and scope, whoever opened it: no unique index backs this, so openPeer takes an advisory lock on the pair and scope before looking for it. Both people are owner members. It takes no Agents and no third person, so messages never route. The list reports peerUserId relative to the viewer. Either account's deletion removes it.

Who may talk (requirePeerRelation, rechecked on every send so a lapsed relation silences the conversation and keeps its history): in the personal space, mutual contacts; in a workspace, two members, or a member and an external contact of the workspace paired with them in user_contacts. Two external contacts never talk to each other there.

Conversations between Agents

channels.agentPairKey (agentA:agentB, sorted) marks the conversation in which one of a person's Agents asks another (openAgentPair). A unique index keeps one per pair, person and scope, whichever Agent opens it. It is group-shaped (agentId NULL): the person is its owner member, and its two Agents are members with the environments the caller passes. It is the only Channel that takes a request written by an Agent (authorAgentMemberId on send): such a row has agentId and no userId while its job's requester stays the person, so execution identity, access and continuation are unchanged. Authorship is isAgentAuthored (a reply, or a row with agentId), not routingStatus alone.

When a reply to an Agent's request is published there, deliverAnswerToAsker queues the asking Agent on that reply, for the same requester. A reply to a reply wakes no one, so an exchange ends with the asking Agent's answer unless it asks again.

Delivery-key retirement rollout

Migration 0197_channel_jobs_message_member_unique enforces one job per message and Agent member, but deliberately retains the physical delivery_key column and its initial default. Older binaries still include that column in ORM reads and writes; new binaries omit it. The generated snapshot and DBML describe the new application schema, not this temporary compatibility column. Do not add the column back to the runtime schema or drop it in this release.

Deploy this version normally; no separate manual database step is required. Only after it has been deployed and all earlier instances, workers and in-flight tasks have drained should a later release drop the column with a custom migration (the generated snapshot already omits it). Do not ship that cleanup in the same deployment, and retire rollback targets that still reference the column before applying it.

The migration fails rather than deleting jobs if historical (message_id, member_id) pairs are duplicated. The migrator transaction restores the previous index and leaves the data and migration history unchanged on failure. Rebuilding the index still takes a table lock; column compatibility does not promise a lock-free migration.

Topic continuation

Every claim reserves a new operation, but normally continues the previous topic for the same Channel Agent member, branch and requesting member. Requester isolation prevents resuming another person's credentials or internal context. The last claimed delivery (ordered by claimedAt, not request sequence) must have accepted input, finished successfully and released its writer without revocation/isolation. Publication may still be pending. Its Agent and execution configuration must still match, and its topic must exist in the same user/workspace scope and not be trashed.

Like the Discord bridge, the main timeline starts a new topic when the previous topic's updatedAt is more than four hours old. This is checked when the next request arrives; it is not a timer and does not delete old topics. Channel Threads keep their topic despite idle time. A request explicitly retried after routing failed may be older than the previous input cutoff; it starts a new topic instead of inheriting later context. Failed/unknown executions, changed environments and unavailable topics also start afresh. An adapter's explicit “new conversation” feature is outside this foundation.

Every dispatch receives the triggering request, its explicit quote, their authors and attachment references, preceded by at most five public messages its topic has not seen (recentContext): those after the last request the topic accepted, minus the reply it published; a new topic gets the latest five. Older public history is read on demand through lobe-channel.readMessages / readMessage in Native runs, or lh channel history / lh channel message in external runtimes. A Thread can read the main prefix through its root plus its own messages; the frozen request cutoff excludes later arrivals. Reads include published Agent answers, including when continuing a private topic. Existing private Agent transcripts stay in their ordinary topic and are never exposed through these tools.

ChannelHistoryRepository binds reads to the live operation and rechecks requester/Agent membership, workspace access, thread availability and revocation under the Channel lock. The caller cannot choose a Channel or Thread. History pages contain at most 20 messages with 2000-character excerpts; individual messages are read in 12000-character chunks. Names and attachments resolve at read time. External operation tokens receive channel:read only for a reserved Channel dispatch; ordinary runs and sub-agents do not inherit it.

Branch concurrency

A member runs one reply per conversation branch (a Thread, or the main timeline) and answers each branch in message order; its branches run alongside each other. candidates returns one queue head per member and branch, and the coordinator settles and claims each branch without waiting on the member's others. A Thread starts only after the member's main-timeline answer to its root, so a follow-up never overtakes the reply it follows. A reply that opens a Thread before its claim runs in that Thread, which leaves the main timeline free for the next request.

These locks are application rules in claimJob, not database constraints, so they can change without a migration. The branch lock is checked under the channel lock, which already serializes every claim of a member. The directory lock spans channels, so claimJob first takes a transaction-scoped advisory lock on the device directory, then looks for a live writer there; the plain index channel_jobs_active_directory_idx keeps that lookup cheap. Nothing else may set writer_held.

Branches still share what a run touches. The directory lock stays per device directory: a second branch of the same member in a Channel-picked directory moves into its own worktree, as for another member. A member without a Channel device runs where the Agent's own settings say, like two ordinary conversations with that Agent.

Pending routing is part of branch FIFO even before a job exists. An earlier undecided message in the same branch, or the Thread's undecided root, blocks later claims there until its recipients are known; other branches are not held. Skipped, failed or stopped routing releases this barrier. A routed message's deferred follow-ups (wake.afterMemberId) are queued as awaiting_primary and claimed only after the same message's primary responder job settles; a deferred claim freezes the primary's published reply id in manifest.primaryReplyMessageId, read by ChannelExecutionRepository.primaryReply, without moving the history cutoff. Branches opened while their root is pending inherit its eventual responders, preserving explicit invitations. Their unmentioned replies stay pending until then, including replies sent with the all-candidate fallback. Stopping a reply still fences it; root completion never revives it.

Access and runtime integration

  • ChannelRepository checks membership, role and workspace scope. Future routers must also authenticate active workspace membership. Agent configuration, execution permission and device grants must be authorized before dispatch; a Channel membership is not Agent authorization.
  • Ordinary models keep their existing user/workspace authorization semantics. There are no Channel-specific constructors, exclusions from search/memory/sharing, or blanket rejection of Channel-triggered operations. Public Channel messages cannot be read through ordinary chat APIs because they live in a different table. Workspace model scope alone is not an Agent permission check: the eventual details endpoint must authorize the Agent/topic using the existing access layer before opening normal topic details. This PR does not introduce that endpoint or grant.
  • The public timeline includes only posted messages and selected final replies. Tool calls, intermediate outputs and reasoning remain in ordinary conversation storage. Opening details is a separate authorized operation, not an expansion of the public timeline.
  • Read new input with ChannelExecutionRepository.input(channelId, jobId) and pass the claim's topic.id, actual requester/Agent and job.operationId into the existing runtime. Persist the internal transcript with ordinary models; never copy all historical Channel input again when continuing. CLI adapters resume from topic.metadata.heteroSessionId.
  • Dispatch with the job's frozen Agent settings and Channel environment, not member.config or a fresh settings lookup. Device routing and working-directory overrides come from the Channel environment whose grant and locks were checked, not the Agent's default device binding. Knowledge and file contents still use the ordinary authorized runtime loaders; they are not copied into this settings snapshot.
  • Call recordStart for the reserved idle operation before acknowledging dispatch. Only an exact user/workspace/topic/Agent match may initialize it. Repeated starts cannot overwrite running or terminal executions. The runtime remains responsible for normal topic activity updates.
  • Acknowledgement records input acceptance; the ordinary runtime owns session metadata. Save the final answer once, then publish its text to channel_messages; publication is idempotent and cannot publish a revoked delivery. Public attachment uploads are authorized and locked before association. Generic file cleanup preserves files still referenced by Channel messages.
  • Job status describes the Channel delivery; execution status/errors/usage live on its operation. Operation completion is not proof that a device process ended. Only releaseWriter after confirmed termination, or retireReservation for an untouched operation, releases the writer. Isolation frees the member's branch but keeps the device/directory lock. Never retry an unknown delivery. retryJob re-queues a failed job at its requester's (or an admin's) request, once its writer is released and nothing was published; the next claim opens a fresh operation. In resume mode it keeps the failed run's topic, and the claim continues there (resumableTopic, with manifest.resumed) while that topic is still the Agent's, in scope, unheld and on the same runtime, device and directory; otherwise it starts like a retry.
  • A job that fails leaves one card in its reply slot (replyError.ts): its opening acknowledgement in the reply's branch turned into the card, else an Agent message under the reply's own request key job:<jobId>, with metadata.replyError. A later failure rewrites that message (attempts, keyed by the failed operation), and publish writes the reply over it, clearing replyError. Each rewrite moves the message to the end of its timeline (a Thread root stays) so it reads as new and unread. Cards carry no mentions and never route; manifests and routing history show other Agents only " did not finish this reply.", and a card does not count as the Agent's last reply for wake rules.
  • A job blocked only by another writer in its member's directory moves its conversation branch (a Thread, or the main timeline) into a git worktree instead of waiting: the coordinator asks the device to cut lobe-channel/<member>-<branch> from that directory's HEAD under ~/.lobehub/worktrees/ (deriveWorktreePath), records it in the member's metadata.worktrees, and claims again. The worktree then is the job's working directory and directory lock, and the branch keeps it for later replies until the member's device or directory changes. The grant still checks the configured directory it was cut from. Work stays on the worktree branch; nothing merges it back. A directory that cannot host one (not a git repo, device without a home path) keeps the job waiting and is not retried for 10 minutes.
  • Existing hard-delete paths already reach Channel rows: Agent deletion (including trash purge, session and group deletion) cascades direct conversations, UserModel.deleteUser removes personal channels and direct conversations, and workspace deletion cascades every channel in it. Cascades do not stop external processes. The integration's channel_preserve_active_writer database trigger rejects any job deletion while writer_held is true, including cascades. Stop replies and confirm physical termination before retrying the deletion. This prevents existing deletion paths from silently dropping a live directory lock; it does not automatically stop external processes on behalf of a destructive operation.
  • Deleting a Channel deletes its jobs/public history, not ordinary conversations or execution records. Deleting a topic/operation clears the corresponding job reference; it does not delete the Channel timeline or release an unconfirmed writer.

Migration and verification

0184_channel_tables is the foundation migration already on canary and must remain unchanged. It creates Channel tables and references existing Agents, topics, operations and files; it does not add columns or indexes to the ordinary chat tables. The integration adds the active-writer deletion guard in 0187_channel_preserve_active_writer, so databases that already applied the foundation receive the guard too. Both migrations are applied by the normal deployment runner; no separate online index step is needed for existing chat tables. Defensive DDL permits replay of this exact schema, not conversion from earlier development-only versions. A separately deployed prototype needs an explicit inventory and conversion plan before cutover.

Focused integration tests cover storage separation, ordinary access boundaries, attachment retention, continuation/expiry, request-only input, bounded history reads, routing, stops and writer locks. Run with PGlite and with PostgreSQL (vitest.config.server.mts); the two concurrent claim/sequence tests require real PostgreSQL row locking. Runtime and UI integration require separate product acceptance; storage tests alone do not verify the user-visible Channel flow.