Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: reorder bots by dragging them

leepokaia90e9fb2c0f5
diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxproj
index 1b2ffbdc..30dec796 100644
--- a/apps/Codync.xcodeproj/project.pbxproj
+++ b/apps/Codync.xcodeproj/project.pbxproj
@@ -48,6 +48,7 @@
8B78A34695AD94109AE82C0F /* CodyncBot-blob-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = D0E552136D473567E0C25ED4 /* CodyncBot-blob-Tint.ttf */; };
8BB3FC79EB798CE4347E6FD3 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 50F314172CC2AD1C5CDC916A /* CodyncKit */; };
921ED46A1643AB90BB3D4CF7 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F99C11684BFBEB49006600A9 /* Session.swift */; };
+ 9230B7E6BFE8FB9D6F547955 /* BotRowDrop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59AE5FF815ED4C3E61279E1 /* BotRowDrop.swift */; };
9638BAA981354C4CE72884A0 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CC3E47D480A5F15CA95C504 /* HostLink.swift */; };
974A5D8D89758A61E7D8D1B6 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BA06CEE98A7CDED62678522 /* Input.swift */; };
980C29719BDE2E874C9AD53A /* CodyncBot-wedge-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C3BB9F034194450254CE14EC /* CodyncBot-wedge-Tint.ttf */; };
@@ -144,6 +145,7 @@
8D16AD9979C77D976BC832D1 /* Driver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Driver.swift; sourceTree = "<group>"; };
8E783FFF5EC2697C16FA2E1B /* CodyncOrb-Ghost.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncOrb-Ghost.ttf"; sourceTree = "<group>"; };
9AD0BD16672E128A4F26272B /* SignInButtons.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInButtons.swift; sourceTree = "<group>"; };
+ A59AE5FF815ED4C3E61279E1 /* BotRowDrop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotRowDrop.swift; sourceTree = "<group>"; };
A65FE0504B741D0B44DB2516 /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };
AAD970B8394F4EDFB85A8936 /* CodyncBot-cloud-Tint.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-cloud-Tint.ttf"; sourceTree = "<group>"; };
AD18A04CD014230F1B7B0535 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
@@ -289,6 +291,7 @@
4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */,
DD3DE9A4EEB369C4F75C9448 /* ActivityGalleryView.swift */,
0582B6169BFC36E4BCD51C0D /* BotListView.swift */,
+ A59AE5FF815ED4C3E61279E1 /* BotRowDrop.swift */,
2A379E88F918744832CF0CB0 /* ComputerSectionGesture.swift */,
6BC00039A6C2C0D3F39A5F67 /* ComputerStatus.swift */,
6FC76D28AB02DF1427D530ED /* LaunchSplash.swift */,
@@ -667,6 +670,7 @@
9BBB2FAEDBD35A83EAB02981 /* AccountSwitcherView.swift in Sources */,
00F78E3DAAF66E8E0933D091 /* ActivityGalleryView.swift in Sources */,
01A1F820EFEE49A8FCCFC3F3 /* BotListView.swift in Sources */,
+ 9230B7E6BFE8FB9D6F547955 /* BotRowDrop.swift in Sources */,
7C20764DC05D499075BC5E8C /* CodyncApp.swift in Sources */,
6BFFA8A75324425132F1FC2C /* ComputerSectionGesture.swift in Sources */,
2002C16E427B4E4E7279E1C4 /* ComputerStatus.swift in Sources */,
diff --git a/apps/desktop/src/renderer/demo/fake-host.ts b/apps/desktop/src/renderer/demo/fake-host.ts
index c6b0bf9a..75479dc1 100644
--- a/apps/desktop/src/renderer/demo/fake-host.ts
+++ b/apps/desktop/src/renderer/demo/fake-host.ts
@@ -238,6 +238,13 @@ export class FakeHost {
case 'createBot':
case 'updateBot':
return { bot: this.saveBot(b as unknown as BotDraft | GroupDraft) }
+ case 'reorderBots': {
+ ;(b.ids as string[]).forEach((id, position) => {
+ const bot = this.bots.get(id)
+ if (bot) this.emitBot(Object.assign(bot, { position }))
+ })
+ return {}
+ }
case 'deleteBot': {
const id = str('botId')
this.bots.delete(id)
diff --git a/apps/desktop/src/renderer/lib/computer-roster.test.ts b/apps/desktop/src/renderer/lib/computer-roster.test.ts
index 62e7f7e7..282e2026 100644
--- a/apps/desktop/src/renderer/lib/computer-roster.test.ts
+++ b/apps/desktop/src/renderer/lib/computer-roster.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { computerSections, moveComputer, orderedComputers } from './computer-roster.ts'
+import { computerSections, moveInOrder, orderedComputers } from './computer-roster.ts'
test('saved computer order survives reconnect order and appends new computers', () => {
const computers = [{ id: 'new' }, { id: 'a' }, { id: 'b' }]
@@ -10,11 +10,11 @@ test('saved computer order survives reconnect order and appends new computers',
test('moving a section works in either direction without losing hidden computers', () => {
const order = ['a', 'hidden', 'b', 'c']
- assert.deepEqual(moveComputer(order, 'a', 'b'), ['hidden', 'b', 'a', 'c'])
- assert.deepEqual(moveComputer(order, 'c', 'a'), ['c', 'a', 'hidden', 'b'])
- assert.deepEqual(moveComputer(order, 'a', 'a'), order)
- assert.deepEqual(moveComputer(order, 'missing', 'b'), order)
- assert.deepEqual(moveComputer(order, 'a', 'missing'), order)
+ assert.deepEqual(moveInOrder(order, 'a', 'b'), ['hidden', 'b', 'a', 'c'])
+ assert.deepEqual(moveInOrder(order, 'c', 'a'), ['c', 'a', 'hidden', 'b'])
+ assert.deepEqual(moveInOrder(order, 'a', 'a'), order)
+ assert.deepEqual(moveInOrder(order, 'missing', 'b'), order)
+ assert.deepEqual(moveInOrder(order, 'a', 'missing'), order)
assert.deepEqual(order, ['a', 'hidden', 'b', 'c'])
})
diff --git a/apps/desktop/src/renderer/lib/computer-roster.ts b/apps/desktop/src/renderer/lib/computer-roster.ts
index 7ae5bf64..c687e66e 100644
--- a/apps/desktop/src/renderer/lib/computer-roster.ts
+++ b/apps/desktop/src/renderer/lib/computer-roster.ts
@@ -4,8 +4,8 @@ export function orderedComputers<T extends { id: string }>(computers: T[], order
return [...computers].sort((a, b) => (ranks.get(a.id) ?? order.length) - (ranks.get(b.id) ?? order.length))
}
-/** Insert at the target's position, preserving hidden computers and unrelated ordering. */
-export function moveComputer(order: string[], id: string, target: string): string[] {
+/** Insert at the target's position, preserving hidden entries and unrelated ordering (computers, bots). */
+export function moveInOrder(order: string[], id: string, target: string): string[] {
const from = order.indexOf(id)
const to = order.indexOf(target)
if (from < 0 || to < 0 || from === to) return order
diff --git a/apps/desktop/src/renderer/lib/slide.ts b/apps/desktop/src/renderer/lib/slide.ts
new file mode 100644
index 00000000..e8be4120
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/slide.ts
@@ -0,0 +1,18 @@
+import { useLayoutEffect, useRef, type RefObject } from 'react'
+import { reduceMotion } from './theme'
+
+/** Slides an element from where it was to where it is now inside its parent (reordered rows and sections). */
+export function useSlide(ref: RefObject<HTMLElement | null>) {
+ const lastTop = useRef<number | null>(null)
+ useLayoutEffect(() => {
+ const element = ref.current
+ const parent = element?.parentElement
+ if (!element || !parent) return
+ // Relative to the parent, so a row doesn't slide again inside a section that is already sliding.
+ const top = element.offsetTop - (parent.offsetParent === element.offsetParent ? parent.offsetTop : 0)
+ if (lastTop.current !== null && top !== lastTop.current && !reduceMotion()) {
+ element.animate([{ transform: `translateY(${lastTop.current - top}px)` }, { transform: 'translateY(0)' }], { duration: 300, easing: 'ease-out' })
+ }
+ lastTop.current = top
+ })
+}
diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.ts
index cd374fcf..086e7781 100644
--- a/apps/desktop/src/renderer/store/app-model.ts
+++ b/apps/desktop/src/renderer/store/app-model.ts
@@ -141,7 +141,7 @@ export class AppModel extends Observable {
return this.stores.get(id) ?? null
}
- /** Every computer's visible bots, pinned first, then most recent activity. */
+ /** Every computer's visible bots, computer by computer, each in its roster order. */
get roster(): RosterItem[] {
const items: RosterItem[] = []
for (const computer of this.computers) {
@@ -149,7 +149,7 @@ export class AppModel extends Observable {
if (!store) continue
for (const bot of store.roster) items.push({ ref: { computerId: computer.id, botId: bot.id }, bot, computer: store.computer, store })
}
- return items.sort((a, b) => (a.bot.pinned !== b.bot.pinned ? (a.bot.pinned ? -1 : 1) : b.bot.lastAt - a.bot.lastAt))
+ return items
}
select(ref: BotRef | null) {
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index 35929389..c7885043 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -103,9 +103,9 @@ export class BotMirror extends Observable {
return null
}
- /** Roster order: pinned first, then most recent activity. */
+ /** Roster order: pinned first, then where the user dragged them, then most recent activity. */
get roster(): Bot[] {
- return [...this.bots.values()].filter((b) => !b.hidden).sort((a, b) => (a.pinned !== b.pinned ? (a.pinned ? -1 : 1) : b.lastAt - a.lastAt))
+ return [...this.bots.values()].filter((b) => !b.hidden).sort((a, b) => Number(b.pinned) - Number(a.pinned) || a.position - b.position || b.lastAt - a.lastAt)
}
get hiddenBots(): Bot[] {
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.ts
index 6b62f2d5..b642f8f5 100644
--- a/apps/desktop/src/renderer/store/bot-store.ts
+++ b/apps/desktop/src/renderer/store/bot-store.ts
@@ -227,6 +227,16 @@ export class BotStore extends BotSync {
this.patchBot(bot, { hidden })
}
+ /** The roster as the user dragged it, top first: shown at once, then saved on the host. */
+ reorder(ids: string[]) {
+ ids.forEach((id, position) => {
+ const bot = this.bots.get(id)
+ if (bot) this.bots.set(id, { ...bot, position })
+ })
+ this.changed()
+ this.perform((c) => c.call('reorderBots', { ids }), true)
+ }
+
delete(bot: Bot) {
this.composerDrafts.removeBot(bot.id)
this.bots.delete(bot.id)
diff --git a/apps/desktop/src/renderer/store/computer-order.ts b/apps/desktop/src/renderer/store/computer-order.ts
index fbba9139..d6e53f2c 100644
--- a/apps/desktop/src/renderer/store/computer-order.ts
+++ b/apps/desktop/src/renderer/store/computer-order.ts
@@ -1,6 +1,6 @@
import { Observable } from '../lib/observable'
import { pref, prefs, type Pref } from '../lib/prefs'
-import { moveComputer } from '../lib/computer-roster'
+import { moveInOrder } from '../lib/computer-roster'
import { account } from './account'
/** This device's order, kept separately for each account and cloud environment. */
@@ -21,7 +21,7 @@ export class DeviceComputerOrder extends Observable {
move(id: string, target: string, computers: string[]) {
const current = [...new Set([...this.ids, ...computers])]
- const next = moveComputer(current, id, target)
+ const next = moveInOrder(current, id, target)
if (next === current) return
if (this.saved) this.saved.set({ ids: next })
else prefs.computerOrder.set(next)
diff --git a/apps/desktop/src/renderer/store/computer-roster.ts b/apps/desktop/src/renderer/store/computer-roster.ts
index 4b6d7412..de80792f 100644
--- a/apps/desktop/src/renderer/store/computer-roster.ts
+++ b/apps/desktop/src/renderer/store/computer-roster.ts
@@ -1,8 +1,8 @@
-import { computerSections, orderedComputers } from '../lib/computer-roster'
+import { computerSections, moveInOrder, orderedComputers } from '../lib/computer-roster'
import { prefs, usePref } from '../lib/prefs'
import { useModel } from '../lib/observable'
import type { BotStore } from './bot-store'
-import type { AppModel } from './app-model'
+import type { AppModel, BotRef } from './app-model'
/** Device-local section ordering and folding, matching the iPhone roster. */
export function useComputerRoster(app: AppModel, shown: Set<string>) {
@@ -25,5 +25,14 @@ export function useComputerRoster(app: AppModel, shown: Set<string>) {
move(id: string, target: string) {
app.computerOrder.move(id, target, computers.map((c) => c.id))
},
+ /** One place up (-1) or down (+1) among its computer's bots with the same pin state. */
+ moveBot(ref: BotRef, offset: number) {
+ const section = sections.find((s) => s.computer.id === ref.computerId)
+ const items = section?.items ?? []
+ const index = items.findIndex((item) => item.bot.id === ref.botId)
+ const target = items[index + offset]
+ if (!section || index < 0 || !target || target.bot.pinned !== items[index]!.bot.pinned) return
+ section.store.reorder(moveInOrder(items.map((item) => item.bot.id), ref.botId, target.bot.id))
+ },
}
}
diff --git a/apps/desktop/src/renderer/views/BotRoster.tsx b/apps/desktop/src/renderer/views/BotRoster.tsx
index 72f3d661..f504af5b 100644
--- a/apps/desktop/src/renderer/views/BotRoster.tsx
+++ b/apps/desktop/src/renderer/views/BotRoster.tsx
@@ -1,5 +1,7 @@
-import { useState } from 'react'
+import { useRef, useState, type DragEvent, type ReactNode } from 'react'
import { isGroup, type Bot } from '@shared/models'
+import { moveInOrder } from '../lib/computer-roster'
+import { useSlide } from '../lib/slide'
import { sameRef, refKey, type RosterItem } from '../store/app-model'
import type { BotStore } from '../store/bot-store'
import type { useComputerRoster } from '../store/computer-roster'
@@ -8,6 +10,12 @@ import { BotRow } from './BotRow'
import { ComputerRosterSection } from './ComputerRosterSection'
import { UpdateNeededCard } from './UpdateNeededCard'
+/** A bot being dragged among its computer's bots, and the order it has made so far. */
+interface BotDrag {
+ item: RosterItem
+ ids: string[]
+}
+
export function BotRoster({ roster, compact, onContext }: {
roster: ReturnType<typeof useComputerRoster>
compact: boolean
@@ -17,46 +25,123 @@ export function BotRoster({ roster, compact, onContext }: {
const selected = app.selection
const [hovered, setHovered] = useState<string | null>(null)
const [dragged, setDragged] = useState<string | null>(null)
- const row = (item: RosterItem) => {
+ const [botDrag, setBotDrag] = useState<BotDrag | null>(null)
+
+ /** A section's rows, in the order a drag in progress has them. */
+ const ordered = (computerId: string, items: RosterItem[]) => {
+ if (botDrag?.item.ref.computerId !== computerId) return items
+ const byId = new Map(items.map((item) => [item.bot.id, item]))
+ return botDrag.ids.flatMap((id) => byId.get(id) ?? [])
+ }
+
+ // Any row of the same computer takes the drop (on enter and over); only rows with the same pin state make room.
+ const dragOver = (event: DragEvent<HTMLElement>, item: RosterItem) => {
+ if (!botDrag || botDrag.item.ref.computerId !== item.ref.computerId) return
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'move'
+ // A row still sliding out of the way would be hit again where it was.
+ if (item.bot.id === botDrag.item.bot.id || item.bot.pinned !== botDrag.item.bot.pinned || event.currentTarget.getAnimations().length) return
+ setBotDrag({ ...botDrag, ids: moveInOrder(botDrag.ids, botDrag.item.bot.id, item.bot.id) })
+ }
+
+ const drop = (event: DragEvent<HTMLElement>) => {
+ if (!botDrag) return
+ event.preventDefault()
+ if (botDrag.ids.some((id, index) => id !== botDrag.item.store.roster[index]?.id)) botDrag.item.store.reorder(botDrag.ids)
+ setBotDrag(null)
+ }
+
+ const row = (item: RosterItem, siblings: RosterItem[]) => {
const key = refKey(item.ref)
const isSelected = sameRef(item.ref, selected)
+ const many = roster.sections.length > 1
return (
- <button
+ <RosterRow
key={key}
- className="roster-row"
- style={{
- padding: compact ? 0 : '0 8px',
- background: isSelected ? 'var(--roster-selected)' : hovered === key ? 'var(--bubble-agent)' : 'transparent',
- }}
- aria-label={roster.sections.length > 1 ? `${item.bot.name}, on ${item.store.hostName}` : item.bot.name}
- aria-selected={isSelected}
- title={roster.sections.length > 1 ? `${item.bot.name} · ${item.store.hostName}` : item.bot.name}
- onMouseEnter={() => setHovered(key)}
- onMouseLeave={() => setHovered((h) => (h === key ? null : h))}
+ dragging={botDrag?.item.bot.id === item.bot.id && botDrag.item.ref.computerId === item.ref.computerId}
+ background={isSelected ? 'var(--roster-selected)' : hovered === key ? 'var(--bubble-agent)' : 'transparent'}
+ compact={compact}
+ label={many ? `${item.bot.name}, on ${item.store.hostName}` : item.bot.name}
+ title={many ? `${item.bot.name} · ${item.store.hostName}` : item.bot.name}
+ selected={isSelected}
+ onHover={(on) => setHovered((h) => (on ? key : h === key ? null : h))}
onClick={() => app.select(item.ref)}
- onContextMenu={(e) => {
- e.preventDefault()
- onContext(item.bot, item.store, e.clientX, e.clientY)
- }}
+ onContext={(x, y) => onContext(item.bot, item.store, x, y)}
+ onDragStart={() => setBotDrag({ item, ids: siblings.map((s) => s.bot.id) })}
+ onDragOver={(event) => dragOver(event, item)}
+ onDrop={drop}
+ onDragEnd={() => setBotDrag(null)}
>
<BotRow bot={item.bot} store={item.store} compact={compact} usingComputer={item.store.screen?.agentBot === item.bot.id} members={isGroup(item.bot) ? item.store.members(item.bot) : noMembers} />
- </button>
+ </RosterRow>
)
}
return roster.sections.map(({ computer, store, items }, index) => {
const notice = store.mismatch && !compact ? <StoreContext.Provider value={store}><UpdateNeededCard /></StoreContext.Provider> : null
- if (!roster.grouped) return <div key={computer.id}>{notice}{items.map(row)}</div>
+ const rows = ordered(computer.id, items).map((item) => row(item, items))
+ if (!roster.grouped) return <div key={computer.id}>{notice}{rows}</div>
return (
<ComputerRosterSection key={computer.id} store={store} compact={compact}
collapsed={roster.collapsed.includes(computer.id)} toggle={() => roster.toggle(computer.id)}
previous={roster.sections[index - 1]?.computer.id} next={roster.sections[index + 1]?.computer.id}
dragged={dragged} setDragged={setDragged} move={roster.move} notice={notice}>
- {items.map(row)}
+ {rows}
{!items.length && !store.mismatch && !compact ? <div className="computer-roster-empty">{store.shownConnection.kind === 'online' ? 'No bots yet' : store.connectionLabel}</div> : null}
</ComputerRosterSection>
)
})
}
+/** One roster button: drags to reorder, and slides when the others move. */
+function RosterRow({ dragging, background, compact, label, title, selected, onHover, onClick, onContext, onDragStart, onDragOver, onDrop, onDragEnd, children }: {
+ dragging: boolean
+ background: string
+ compact: boolean
+ label: string
+ title: string
+ selected: boolean
+ onHover: (on: boolean) => void
+ onClick: () => void
+ onContext: (x: number, y: number) => void
+ onDragStart: () => void
+ onDragOver: (event: DragEvent<HTMLElement>) => void
+ onDrop: (event: DragEvent<HTMLElement>) => void
+ onDragEnd: () => void
+ children: ReactNode
+}) {
+ const ref = useRef<HTMLButtonElement>(null)
+ useSlide(ref)
+ return (
+ <button
+ ref={ref}
+ className={`roster-row ${dragging ? 'dragging' : ''}`}
+ style={{ padding: compact ? 0 : '0 8px', background }}
+ aria-label={label}
+ aria-selected={selected}
+ title={title}
+ draggable
+ onMouseEnter={() => onHover(true)}
+ onMouseLeave={() => onHover(false)}
+ onClick={onClick}
+ onContextMenu={(e) => {
+ e.preventDefault()
+ onContext(e.clientX, e.clientY)
+ }}
+ onDragStart={(e) => {
+ // Its own type, so the composer and other apps don't take it as text.
+ e.dataTransfer.effectAllowed = 'move'
+ e.dataTransfer.setData('application/x-codync-bot', label)
+ onDragStart()
+ }}
+ onDragEnter={onDragOver}
+ onDragOver={onDragOver}
+ onDrop={onDrop}
+ onDragEnd={onDragEnd}
+ >
+ {children}
+ </button>
+ )
+}
+
const noMembers: Bot[] = []
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 8fdadd1a..78e19a0a 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -240,10 +240,15 @@ function ChatSplitView() {
{ title: 'Delete', icon: 'trash', destructive: true, action: () => setConfirmDelete({ bot, store }) },
]
- // ↑/↓ in the roster move the selection.
+ // ↑/↓ in the roster move the selection; Alt+↑/↓ moves the selected bot itself.
const onListKey = (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
if (e.target instanceof HTMLElement && e.target.closest('.computer-roster-heading')) return
+ if (e.altKey) {
+ e.preventDefault()
+ if (app.selection) roster.moveBot(app.selection, e.key === 'ArrowUp' ? -1 : 1)
+ return
+ }
const refs = roster.navigable.map((i) => i.ref)
if (!refs.length) return
e.preventDefault()
diff --git a/apps/desktop/src/renderer/views/ComputerRosterSection.tsx b/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
index d652054c..07991881 100644
--- a/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
+++ b/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
@@ -1,6 +1,6 @@
-import { useLayoutEffect, useRef, type ReactNode } from 'react'
+import { useRef, type ReactNode } from 'react'
import { Icon } from '../components/Icon'
-import { reduceMotion } from '../lib/theme'
+import { useSlide } from '../lib/slide'
import type { BotStore } from '../store/bot-store'
import { ComputerBadge } from './ComputerBadge'
import './computer-roster.css'
@@ -21,17 +21,8 @@ interface Props {
export function ComputerRosterSection({ store, compact, collapsed, previous, next, dragged, setDragged, toggle, move, notice, children }: Props) {
const section = useRef<HTMLElement>(null)
- const lastTop = useRef<number | null>(null)
const id = store.computer.id
- useLayoutEffect(() => {
- const element = section.current
- if (!element) return
- const top = element.offsetTop
- if (lastTop.current !== null && top !== lastTop.current && !reduceMotion()) {
- element.animate([{ transform: `translateY(${lastTop.current - top}px)` }, { transform: 'translateY(0)' }], { duration: 300, easing: 'ease-out' })
- }
- lastTop.current = top
- })
+ useSlide(section)
return (
<section ref={section} className={`computer-roster-section ${dragged === id ? 'dragging' : ''}`} aria-label={store.hostName}
onDragOver={(event) => {
diff --git a/apps/desktop/src/renderer/views/chat-window.css b/apps/desktop/src/renderer/views/chat-window.css
index 3a47a8c9..68616c4f 100644
--- a/apps/desktop/src/renderer/views/chat-window.css
+++ b/apps/desktop/src/renderer/views/chat-window.css
@@ -61,6 +61,9 @@
transition: background-color var(--hover);
flex: none;
}
+.roster-row.dragging {
+ opacity: 0.45;
+}
/* A selected row's fill doesn't touch its hovered neighbour's. */
.roster-row + .roster-row {
margin-top: 4px;
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 954183d9..12088583 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -21,6 +21,8 @@ export interface Bot {
permission: string
model?: string | null
pinned: boolean
+ /** Where the user dragged it, lowest first (after pinned bots); ties sort by recent activity. */
+ position: number
hidden: boolean
notify?: boolean | null
connectors: string[]
@@ -58,6 +60,7 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
permission: raw.permission ?? 'auto',
model: raw.model ?? null,
pinned: raw.pinned ?? false,
+ position: raw.position ?? 0,
hidden: raw.hidden ?? false,
notify: raw.notify ?? null,
connectors: raw.connectors ?? [],
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 6d132389..c1ea9838 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -191,6 +191,11 @@ public extension HostClient {
let _: Empty = try await call("deleteBot", ["botId": id])
}
+ /// The roster as the user dragged it, top first.
+ func reorderBots(_ ids: [String]) async throws {
+ let _: Empty = try await call("reorderBots", ["ids": ids])
+ }
+
/// The main chat, one thread (`threadId`), or everything (`all`).
func markRead(_ id: String, threadId: String? = nil, all: Bool = false) async throws {
struct Body: Encodable { var botId: String; var threadId: String?; var all: Bool }
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
index 0407167b..5c30cad4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
@@ -22,6 +22,8 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var permission: String
public var model: String?
public var pinned: Bool
+ /// Where the user dragged it, lowest first (after pinned bots); ties sort by recent activity.
+ public var position: Int = 0
public var hidden: Bool
public var notify: Bool?
/// Installed connector / skill ids this bot uses (see `Market.swift`).
@@ -399,6 +401,7 @@ extension Bot {
permission = try c.decodeIfPresent(String.self, forKey: .permission) ?? "auto"
model = try c.decodeIfPresent(String.self, forKey: .model)
pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? false
+ position = try c.decodeIfPresent(Int.self, forKey: .position) ?? 0
hidden = try c.decodeIfPresent(Bool.self, forKey: .hidden) ?? false
notify = try c.decodeIfPresent(Bool.self, forKey: .notify)
connectors = try c.decodeIfPresent([String].self, forKey: .connectors) ?? []
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index de639ec3..c1d680b0 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -78,7 +78,7 @@ public final class AccountStore {
// MARK: derived
- /// Every computer's visible bots, pinned first, then most recent activity.
+ /// Every computer's visible bots, computer by computer, each in its roster order.
public var roster: [RosterItem] {
computers.flatMap { computer -> [RosterItem] in
guard let store = stores[computer.id] else { return [] }
@@ -86,10 +86,6 @@ public final class AccountStore {
RosterItem(ref: BotReference(accountId: accountId, computerId: computer.id, botId: $0.id), bot: $0, computer: store.computer)
}
}
- .sorted {
- if $0.bot.pinned != $1.bot.pinned { return $0.bot.pinned }
- return $0.bot.lastAt > $1.bot.lastAt
- }
}
public func store(for id: ComputerID) -> BotStore? { stores[id] }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index 98026b8c..9bcd16f8 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -175,6 +175,47 @@ extension BotStore {
perform(replay: true) { _ = try await $0.updateBot(d) }
}
+ // MARK: roster order
+
+ /// Moves a dragged bot into `target`'s place, among bots with the same pin state. Shown at
+ /// once; sent when the drag is dropped (`saveOrder`), or once it has been still a moment.
+ @discardableResult
+ public func move(_ botId: String, onto target: String) -> Bool {
+ var ids = roster.map(\.id)
+ guard botId != target, bots[botId]?.pinned == bots[target]?.pinned,
+ let from = ids.firstIndex(of: botId), let to = ids.firstIndex(of: target) else { return false }
+ ids.remove(at: from)
+ ids.insert(botId, at: to)
+ reorder(ids)
+ orderSave = Task { [weak self] in
+ // ponytail: a pause mid-drag sends early; the host's echo can briefly undo a move made right after.
+ try? await Task.sleep(for: .seconds(1.5))
+ if !Task.isCancelled { self?.saveOrder() }
+ }
+ return true
+ }
+
+ /// One place up (-1) or down (+1) among bots with the same pin state (VoiceOver), sent now.
+ public func move(_ botId: String, by offset: Int) {
+ let ids = roster.map(\.id)
+ guard let i = ids.firstIndex(of: botId), ids.indices.contains(i + offset), move(botId, onto: ids[i + offset]) else { return }
+ saveOrder()
+ }
+
+ /// Sends a dragged order that hasn't been sent.
+ public func saveOrder() {
+ guard let pending = orderSave else { return }
+ pending.cancel()
+ orderSave = nil
+ let ids = roster.map(\.id)
+ perform(replay: true) { try await $0.reorderBots(ids) }
+ }
+
+ private func reorder(_ ids: [String]) {
+ orderSave?.cancel()
+ for (position, id) in ids.enumerated() { bots[id]?.position = position }
+ }
+
public func delete(_ bot: Bot) {
removeComposerDrafts(for: bot.id)
bots[bot.id] = nil
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
index efdc63d6..78b86dfd 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
@@ -68,6 +68,8 @@ public final class BotStore {
/// Bots whose older history has been fully paged in.
public internal(set) var historyComplete: Set<String> = []
var composerDrafts: [String: String] = [:]
+ /// A dragged order not sent yet (see `reorder`).
+ var orderSave: Task<Void, Never>?
public var routineDrafts: [String: String] = [:]
public let fileDownloads = FileDownloads()
public var lastError: String?
@@ -190,10 +192,11 @@ public final class BotStore {
return nil
}
- /// Roster order: pinned first (manual order not tracked yet), then most recent activity.
+ /// Roster order: pinned first, then where the user dragged them, then most recent activity.
public var roster: [Bot] {
bots.values.filter { !$0.hidden }.sorted {
if $0.pinned != $1.pinned { return $0.pinned }
+ if $0.position != $1.position { return $0.position < $1.position }
return $0.lastAt > $1.lastAt
}
}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
new file mode 100644
index 00000000..ed713ab9
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
@@ -0,0 +1,27 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+@MainActor @Test func draggingKeepsBotsAmongTheSamePinState() throws {
+ let suite = "RosterOrderTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
+ let store = BotStore(computer: Computer(id: UUID().uuidString, name: "Mac", signKey: "test"), clientKind: "ios", storage: storage) {
+ FakeRemote(.connecting)
+ }
+ defer { store.retire() }
+ for (id, pinned, lastAt) in [("p", true, 0), ("a", false, 3), ("b", false, 2), ("c", false, 1)] {
+ let json = #"{"id":"\#(id)","pinned":\#(pinned),"lastAt":\#(lastAt)}"#
+ store.bots[id] = try JSONDecoder().decode(Bot.self, from: Data(json.utf8))
+ }
+ let order = { store.roster.map(\.id) }
+ #expect(order() == ["p", "a", "b", "c"]) // Never arranged: recent activity.
+ #expect(store.move("c", onto: "a"))
+ #expect(order() == ["p", "c", "a", "b"])
+ #expect(store.orderSave != nil) // Sent on drop, not on every pass.
+ #expect(!store.move("a", onto: "p")) // An unpinned bot stays below the pinned ones.
+ store.move("b", by: -1)
+ #expect(order() == ["p", "c", "b", "a"])
+ #expect(store.orderSave == nil)
+}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 6cef47ec..6e75537e 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -13,6 +13,8 @@ struct BotListView: View {
@State private var drag: SectionDrag?
/// Each computer section's height, to work out where a dragged one lands.
@State private var sectionHeights: [ComputerID: CGFloat] = [:]
+ /// The bot row being dragged among its computer's bots (see `BotRowDrop`).
+ @State private var draggingBot: BotReference?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// Computers left out of the list on this device, comma-separated IDs.
@AppStorage("hiddenComputers") private var hiddenComputers = ""
@@ -113,6 +115,7 @@ struct BotListView: View {
.scrollDisabled(drag != nil)
.sensoryFeedback(.impact(weight: .medium), trigger: drag?.id) { _, new in new != nil }
.sensoryFeedback(.selection, trigger: drag.map { landingIndex(shownStores.map(\.computer.id), $0) })
+ .sensoryFeedback(.selection, trigger: roster.map(\.id)) { _, _ in draggingBot != nil }
.background(Palette.background)
.navigationTitle("Bots")
.navigationBarTitleDisplayMode(.inline)
@@ -241,6 +244,10 @@ struct BotListView: View {
}
.buttonStyle(.plain)
.accessibilityLabel(accounts.computers.count > 1 ? "\(bot.name), on \(store.hostName)" : bot.name)
+ .accessibilityActions {
+ Button("Move up") { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { store.move(bot.id, by: -1) } }
+ Button("Move down") { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { store.move(bot.id, by: 1) } }
+ }
.contextActions {
[
MenuItem(bot.pinned ? "Unpin" : "Pin", icon: bot.pinned ? "pin.slash" : "pin") { store.setPinned(bot, !bot.pinned) },
@@ -252,6 +259,12 @@ struct BotListView: View {
MenuItem("Delete", icon: "trash", destructive: true, divider: true) { confirmDelete = item },
]
}
+ // Touch and hold, then drag: the menu gives way to the drag (iOS's usual pairing).
+ .onDrag {
+ draggingBot = item.ref
+ return NSItemProvider(object: bot.name as NSString)
+ }
+ .onDrop(of: [.text], delegate: BotRowDrop(target: item, store: store, dragging: $draggingBot, reduceMotion: reduceMotion))
}
/// A group chat gathers bots of one computer (the first one online; more computers are future work).
diff --git a/apps/ios/Views/BotRowDrop.swift b/apps/ios/Views/BotRowDrop.swift
new file mode 100644
index 00000000..840ead7d
--- /dev/null
+++ b/apps/ios/Views/BotRowDrop.swift
@@ -0,0 +1,32 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// A bot row others can be dragged onto, to reorder a computer's bots. It's a system drag,
+/// so touch and hold still opens the row's menu first. The store moves the dragged bot into
+/// each row it passes; the drop sends the order.
+struct BotRowDrop: DropDelegate {
+ let target: RosterItem
+ let store: BotStore
+ @Binding var dragging: BotReference?
+ let reduceMotion: Bool
+
+ func validateDrop(info: DropInfo) -> Bool {
+ dragging?.computerId == target.ref.computerId
+ }
+
+ func dropEntered(info: DropInfo) {
+ guard let dragging, dragging.computerId == target.ref.computerId else { return }
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { _ = store.move(dragging.botId, onto: target.bot.id) }
+ }
+
+ func dropUpdated(info: DropInfo) -> DropProposal? {
+ DropProposal(operation: .move)
+ }
+
+ func performDrop(info: DropInfo) -> Bool {
+ store.saveOrder()
+ dragging = nil
+ return true
+ }
+}
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 595c5227..545eec60 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -46,8 +46,10 @@ status and update notices in each section. Drag a heading or press Alt+Up/Down o
heading to reorder sections. Click a heading to fold its bots.
Order and folded sections stay on this device; the iPhone and other computers keep
independent orders even when signed in to the same account. Filtering a computer out
-does not discard its position. One selected computer keeps a flat roster. Bot pin/activity
-ordering stays within each section, and arrow-key navigation skips folded sections.
+does not discard its position. One selected computer keeps a flat roster. Bots stay within
+their computer's section; drag a bot row or press Alt+Up/Down on the selected bot to reorder
+it ([bot order](../features/computer-order.md#bot-order), synced through the host), and
+arrow-key navigation skips folded sections.
Search still includes their bots. The compact sidebar uses computer badges for the same
section controls. Ordering is saved locally immediately and survives restart, with separate
preferences per account and cloud environment. See [computer ordering](../features/computer-order.md).
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 1c82e2fc..a8e0edd2 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -10,7 +10,7 @@ iPhone conversation scrolling leaves dragging, deceleration, and bottom rubber-b
Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.
-Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (link handling in `apps/desktop/src/renderer/store/bot-sync.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration, automatic access requests) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to lift the whole section and drag it up or down; the other sections slide out of its way and the order is saved on the device on release (`AccountStore.move`; VoiceOver: Move up / Move down). The desktop app shows a flat roster. There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.
+Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (link handling in `apps/desktop/src/renderer/store/bot-sync.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration, automatic access requests) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then in the order the user dragged them into, then by recency ([bot order](../features/computer-order.md#bot-order)). On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to lift the whole section and drag it up or down; the other sections slide out of its way and the order is saved on the device on release (`AccountStore.move`; VoiceOver: Move up / Move down). The desktop app shows a flat roster. There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.
Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Bots/ComputerFilterHeader.swift`, `Store/ComputerSelection.swift`, `Bots/BotRow.swift`; desktop: `apps/desktop/src/renderer/views/ChatWindow.tsx`, `ComputerFilterHeader.tsx`, `BotRow.tsx`.
diff --git a/docs/features/analytics.md b/docs/features/analytics.md
index 7652e048..5552b5c8 100644
--- a/docs/features/analytics.md
+++ b/docs/features/analytics.md
@@ -23,7 +23,7 @@ Settings anytime. The public promise lives in `web/app/privacy/page.tsx`: keep i
- **Host** (`host/src/analytics.rs`): `api::dispatch` maps successful API calls to events
(`analytics::observe`), so every client is covered once: `bot_created`, `bot_updated`,
- `bot_deleted`, `message_sent`, `turn_stopped`, `session_reset`, `permission_answered`,
+ `bots_reordered`, `bot_deleted`, `message_sent`, `turn_stopped`, `session_reset`, `permission_answered`,
`routine_saved`, `routine_deleted`, `routine_run`, `voice_call_finished`,
`remote_screen_opened`, `connector_installed`, `skill_installed`. `client` is `local`
(desktop app, terminal UI) or `remote` (phones). Batches go to `/batch/` every 30 s.
diff --git a/docs/features/computer-order.md b/docs/features/computer-order.md
index c9d0260a..a1e57228 100644
--- a/docs/features/computer-order.md
+++ b/docs/features/computer-order.md
@@ -37,3 +37,18 @@ The account computer-order API has been removed. Migration
unused. Updating clients stops them from reading or writing remote order immediately,
without requiring a cloud deployment. Removing the endpoint from an existing Worker
requires deploying the updated cloud code separately.
+
+## Bot order
+
+A computer's bots (and group chats) keep the order the user drags them into, on every
+device: the host stores it as each bot's `position` (`reorderBots`, `host/src/hub/order.rs`)
+and syncs it like any bot change. Pinned bots stay above the rest, and a bot moves only
+among bots with the same pin state. Until a computer's bots are first arranged, every
+position is 0 and they sort by recent activity; after that they stay put and a new bot
+appears on top. Hidden bots keep their position for when they return.
+
+- **iPhone:** touch and hold a row, then drag it (the row's menu gives way to the drag, as
+ elsewhere in iOS). Rows move out of the way as it passes; the drop saves the order
+ (`BotStore.move(_:onto:)`, `apps/ios/Views/BotRowDrop.swift`). VoiceOver: Move up / Move down.
+- **Desktop:** drag a row, or Alt+Up/Down on the selected bot (macOS, Linux, Windows).
+- **Terminal UI:** `J` / `K` move the selected bot down / up.
diff --git a/docs/features/groups-and-threads.md b/docs/features/groups-and-threads.md
index bf6067c9..2e671750 100644
--- a/docs/features/groups-and-threads.md
+++ b/docs/features/groups-and-threads.md
@@ -37,6 +37,7 @@ replies itself.
| `createBot` | `{kind:"group", name, description?, members}` | Returns the existing group when these exact bots already share one. |
| `updateBot` | `{id, name?, members?, pinned?, hidden?}` | A group can't become a bot or the reverse. |
| `deleteBot` | `botId` | A group's bots stay. A deleted bot leaves its groups. |
+| `reorderBots` | `ids` | The roster as the user dragged it, top first; groups count as rows. See [bot order](computer-order.md#bot-order). |
| `stop` | `botId` | For a group: ends its room turns (main and threads) and stops members working in it. |
| `react` | `entryId, emoji` | Toggles the user's reaction on a chat message (`data.reactions`, oldest first, at most 8). A reacted-to message never turns unread again. The bot isn't told. |
| `respondPermission` | `entryId, optionId?` | Routed to `data.author`, so cards in a group reach the bot that asked. |
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 1bd192e8..49b6cb13 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -34,6 +34,7 @@ pub enum Event {
SignedOut,
BotCreated,
BotUpdated,
+ BotsReordered,
BotDeleted,
MessageSent,
TurnStopped,
@@ -57,6 +58,7 @@ impl Event {
Self::SignedOut => "signed_out",
Self::BotCreated => "bot_created",
Self::BotUpdated => "bot_updated",
+ Self::BotsReordered => "bots_reordered",
Self::BotDeleted => "bot_deleted",
Self::MessageSent => "message_sent",
Self::TurnStopped => "turn_stopped",
@@ -136,6 +138,7 @@ pub fn observe(caller: &Caller, method: &str, b: &Value) -> Option<(Event, Map<S
Event::BotCreated
}
"updateBot" => Event::BotUpdated,
+ "reorderBots" => Event::BotsReordered,
"deleteBot" => Event::BotDeleted,
"send" => {
let in_thread = b["threadId"].as_str().is_some_and(|t| !t.is_empty());
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index 25b90a59..192afa55 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -93,6 +93,13 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
let hub = hub.clone();
json!({"bot": tokio::task::spawn_blocking(move || hub.update_bot(&b)).await??})
}
+ // The roster as the user dragged it, top first.
+ "reorderBots" => {
+ let ids: Vec<String> = serde_json::from_value(b["ids"].clone()).context("ids is required")?;
+ let hub = hub.clone();
+ tokio::task::spawn_blocking(move || hub.reorder_bots(&ids)).await??;
+ json!({})
+ }
"deleteBot" => {
hub.delete_bot(str_arg(&b, "botId")?)?;
json!({})
diff --git a/host/src/hub.rs b/host/src/hub.rs
index e64c3cb1..9a73f550 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -18,6 +18,7 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{broadcast, watch};
+mod order;
mod sync;
/// What a bot is doing right now (wire values: `idle` / `working` / `needsInput` / `error`).
@@ -184,6 +185,7 @@ impl Hub {
pub fn create_bot(self: &Arc<Self>, mut cfg: BotConfig) -> Result<Value> {
cfg.id = uuid::Uuid::new_v4().to_string();
cfg.created_at = crate::store::now_ms();
+ cfg.position = self.new_bot_position()?;
// No name yet (Grok Bot's flow): it gets one after its first few conversations.
cfg.auto_name = !cfg.is_group() && cfg.name.trim().is_empty();
if cfg.auto_name {
diff --git a/host/src/hub/order.rs b/host/src/hub/order.rs
new file mode 100644
index 00000000..fcee329f
--- /dev/null
+++ b/host/src/hub/order.rs
@@ -0,0 +1,62 @@
+//! The roster's manual order: where the user dragged each bot.
+
+use super::Hub;
+use crate::LockExt;
+use anyhow::Result;
+
+impl Hub {
+ /// Puts `ids` (the roster as shown, top first) in that order. Unknown and deleted ids are
+ /// skipped; bots left out (hidden ones) keep their place.
+ pub fn reorder_bots(&self, ids: &[String]) -> Result<()> {
+ for (position, id) in (0_i64..).zip(ids) {
+ let Some(mut row) = self.store.bot(id)?.filter(|r| !r.deleted) else { continue };
+ if row.config.position == position {
+ continue;
+ }
+ row.config.position = position;
+ {
+ let _g = self.emit_lock.locked();
+ self.store.save_bot(&row.config)?;
+ }
+ self.emit_bot(id);
+ }
+ Ok(())
+ }
+
+ /// A new bot goes on top once the user has arranged the roster; until then it stays at 0,
+ /// so recent activity keeps ordering everything.
+ pub(super) fn new_bot_position(&self) -> Result<i64> {
+ let positions: Vec<i64> =
+ self.store.bots()?.into_iter().filter(|b| !b.deleted).map(|b| b.config.position).collect();
+ let arranged = positions.iter().any(|&p| p != 0);
+ Ok(if arranged { positions.iter().min().copied().unwrap_or(0) - 1 } else { 0 })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::hub::Hub;
+ use crate::remote::identity::Identity;
+ use crate::store::{BotConfig, Store};
+
+ #[tokio::test]
+ async fn dragged_order_sticks_and_new_bots_go_on_top() {
+ let dir = std::env::temp_dir().join(format!("codync-order-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let hub = Hub::new(store, "order-test".into(), Identity::load_or_create(&dir).unwrap(), "test".into(), 0);
+ for id in ["a", "b", "c"] {
+ let cfg: BotConfig =
+ serde_json::from_value(serde_json::json!({"id": id, "name": id, "backend": "claude", "cwd": "/tmp"}))
+ .unwrap();
+ hub.store.save_bot(&cfg).unwrap();
+ }
+ assert_eq!(hub.new_bot_position().unwrap(), 0, "unarranged: recent activity orders new bots too");
+
+ hub.reorder_bots(&["c".into(), "a".into(), "gone".into(), "b".into()]).unwrap();
+ let position = |id: &str| hub.store.bot(id).unwrap().unwrap().config.position;
+ assert!(position("c") < position("a") && position("a") < position("b"));
+ assert_eq!(hub.new_bot_position().unwrap(), -1, "arranged: a new bot goes on top");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/host/src/store/bots.rs b/host/src/store/bots.rs
index cf9f9343..6c7ec171 100644
--- a/host/src/store/bots.rs
+++ b/host/src/store/bots.rs
@@ -215,6 +215,7 @@ mod tests {
permission: Permission::Ask,
model: None,
pinned: false,
+ position: 0,
hidden: false,
notify: None,
connectors: vec![],
diff --git a/host/src/store/model.rs b/host/src/store/model.rs
index 149f0ea0..91e6fd0b 100644
--- a/host/src/store/model.rs
+++ b/host/src/store/model.rs
@@ -82,6 +82,10 @@ pub struct BotConfig {
pub model: Option<String>,
#[serde(default)]
pub pinned: bool,
+ /// Place in the roster, lowest first (after pinned bots). All 0 until the user drags one:
+ /// ties sort by recent activity (see `Hub::reorder_bots`).
+ #[serde(default)]
+ pub position: i64,
#[serde(default)]
pub hidden: bool,
#[serde(default)]
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index dc476113..0f80c044 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -187,6 +187,8 @@ impl App {
KeyCode::Char('u') => self.jump(Mark::Unread),
KeyCode::Char('[') => self.move_bot(-1),
KeyCode::Char(']') => self.move_bot(1),
+ KeyCode::Char('K') => self.reorder_bot(-1),
+ KeyCode::Char('J') => self.reorder_bot(1),
KeyCode::Char(c @ '1'..='9') => {
let i = (c as usize) - ('1' as usize);
let pending = if roster_page { None } else { self.pending().map(|e| (e.id.clone(), e.options())) };
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index c16884f9..566c3c50 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -170,10 +170,16 @@ impl App {
// ---------- derived ----------
- /// Roster order: pinned first, then most recent (same as the phone).
+ /// Roster order: pinned first, then where the user put them, then most recent (same as the phone).
pub fn roster(&self) -> Vec<&Bot> {
let mut v: Vec<&Bot> = self.bots.values().filter(|b| !b.hidden).collect();
- v.sort_by(|a, b| b.pinned.cmp(&a.pinned).then(b.last_at.cmp(&a.last_at)).then(a.name.cmp(&b.name)));
+ v.sort_by(|a, b| {
+ b.pinned
+ .cmp(&a.pinned)
+ .then(a.position.cmp(&b.position))
+ .then(b.last_at.cmp(&a.last_at))
+ .then(a.name.cmp(&b.name))
+ });
v
}
diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rs
index 82c4a219..d127fe57 100644
--- a/host/src/tui/app/model.rs
+++ b/host/src/tui/app/model.rs
@@ -94,6 +94,8 @@ pub struct Bot {
pub auto: bool,
pub model: Option<String>,
pub pinned: bool,
+ /// Where the user dragged it (see `App::roster`).
+ pub position: i64,
pub hidden: bool,
pub notify: bool,
pub computer: bool,
@@ -137,6 +139,7 @@ impl Bot {
auto: v["permission"] == "auto",
model: v["model"].as_str().filter(|m| !m.is_empty()).map(str::to_owned),
pinned: v["pinned"].as_bool().unwrap_or(false),
+ position: v["position"].as_i64().unwrap_or(0),
hidden: v["hidden"].as_bool().unwrap_or(false),
notify: v["notify"].as_bool().unwrap_or(true),
computer: v["computer"].as_bool().unwrap_or(false),
diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rs
index 655b77b8..cb60e280 100644
--- a/host/src/tui/app/navigate.rs
+++ b/host/src/tui/app/navigate.rs
@@ -231,6 +231,24 @@ impl App {
self.thread = Some(root);
}
+ /// Moves the selected bot one place up (-1) or down (+1), staying among bots with its pin
+ /// state, and saves the order. Shown at once; the host's bot events confirm it.
+ pub(super) fn reorder_bot(&mut self, d: isize) {
+ let roster: Vec<(String, bool)> = self.roster().iter().map(|b| (b.id.clone(), b.pinned)).collect();
+ let Some(i) = self.selected.as_ref().and_then(|s| roster.iter().position(|(id, _)| id == s)) else { return };
+ let Some(j) = i.checked_add_signed(d).filter(|&j| j < roster.len() && roster[j].1 == roster[i].1) else {
+ return;
+ };
+ let mut ids: Vec<String> = roster.into_iter().map(|(id, _)| id).collect();
+ ids.swap(i, j);
+ for (position, id) in (0_i64..).zip(&ids) {
+ if let Some(b) = self.bots.get_mut(id) {
+ b.position = position;
+ }
+ }
+ self.call("reorderBots", json!({"ids": ids}), After::Nothing);
+ }
+
pub(super) fn copy_last(&mut self) {
let Some(id) = self.selected.clone() else { return };
let Some(text) = self.lane(&id).into_iter().rev().find(|e| e.is_final()).map(|e| e.text().to_owned()) else {
@@ -241,3 +259,27 @@ impl App {
self.flash("Copied the last reply");
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{Bot, test_app};
+ use serde_json::json;
+
+ #[tokio::test]
+ async fn reordering_stays_among_bots_with_the_same_pin_state() {
+ let mut app = test_app();
+ for (id, pinned, last_at) in [("p", true, 0), ("a", false, 3), ("b", false, 2), ("c", false, 1)] {
+ let bot =
+ Bot::parse(&json!({"id": id, "pinned": pinned, "lastAt": last_at})).expect("a bot with an id parses");
+ app.bots.insert(id.into(), bot);
+ }
+ let order = |app: &super::App| app.roster().iter().map(|b| b.id.clone()).collect::<Vec<_>>();
+ assert_eq!(order(&app), ["p", "a", "b", "c"], "unarranged: recent activity");
+ app.selected = Some("c".into());
+ app.reorder_bot(-1);
+ assert_eq!(order(&app), ["p", "a", "c", "b"]);
+ app.selected = Some("a".into());
+ app.reorder_bot(-1);
+ assert_eq!(order(&app), ["p", "a", "c", "b"], "an unpinned bot can't move above a pinned one");
+ }
+}
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index 70e01c10..f330db0e 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -9,7 +9,7 @@ use super::buffer::{centered, frame_box, put, u};
use super::overlay::field_line;
use super::style::theme;
-const HELP: [(&str, &str, &str); 54] = [
+const HELP: [(&str, &str, &str); 55] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -48,6 +48,7 @@ const HELP: [(&str, &str, &str); 54] = [
("BOTS", "m", "new group chat"),
("BOTS", "e", "edit bot or group"),
("BOTS", "p", "pin / unpin"),
+ ("BOTS", "J K", "move bot down / up"),
("BOTS", "S", "new session"),
("BOTS", "M", "memory"),
("BOTS", "R", "routines"),
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index 38f1b5b7..7efda563 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -27,6 +27,7 @@
"event:bot.bot.notify": "null",
"event:bot.bot.permission": "string",
"event:bot.bot.pinned": "bool",
+ "event:bot.bot.position": "number",
"event:bot.bot.rev": "number",
"event:bot.bot.skills": "array",
"event:bot.bot.startedAt": "null",