The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
import type { LayoutNode } from '@/components/pane-shell/tree/model'
import { TILE_PANE_PREFIX } from './session-focus'
/** Reorder tiles to match layout-tree encounter order (stored ids in the order
* their `session-tile:` panes are walked). Restore replays the array through
* sequential adoption (each center tile APPENDS after the ones before it), so
* array order IS strip order — no `before` stamping needed; a stale `before`
* naming an absent pane falls back to append anyway (see insertAtGroup). Tiles
* not yet adopted sort after placed ones, stably. Returns `null` when nothing
* moves so callers can skip a needless persist. */
export function orderTilesByTree<T extends { storedSessionId: string }>(
tree: LayoutNode | null,
tiles: readonly T[]
): null | T[] {
if (!tree || tiles.length < 2) {
return null
}
const order: string[] = []
const walk = (node: LayoutNode) => {
if (node.type === 'group') {
for (const id of node.panes) {
if (id.startsWith(TILE_PANE_PREFIX)) {
order.push(id.slice(TILE_PANE_PREFIX.length))
}
}
return
}
node.children.forEach(walk)
}
walk(tree)
const rank = new Map(order.map((id, i) => [id, i]))
const next = [...tiles].sort(
(a, b) => (rank.get(a.storedSessionId) ?? Infinity) - (rank.get(b.storedSessionId) ?? Infinity)
)
return next.some((t, i) => t !== tiles[i]) ? next : null
}