The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 2 | import { |
| 3 | generateSpreadPinOrderKeys, |
| 4 | pinOrderKeyBetween, |
| 5 | planPinnedReorder, |
| 6 | } from "@t3tools/client-runtime/state/thread-sort"; |
| 7 | import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; |
| 8 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 9 | import { msg } from "gt-react-native"; |
| 10 | |
| 11 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 12 | |
| 13 | export type ThreadMoveDestination = |
| 14 | | "up" |
| 15 | | "down" |
| 16 | | { |
| 17 | readonly targetId: string | null; |
| 18 | readonly section?: "pinned" | "active" | "settled"; |
| 19 | readonly placement: "before" | "after"; |
| 20 | }; |
| 21 | |
| 22 | export function threadOrderAfterMove( |
| 23 | orderedIds: readonly string[], |
| 24 | movedId: string, |
| 25 | destination: ThreadMoveDestination, |
| 26 | ): string[] | null { |
| 27 | if (typeof destination === "object" && destination.section === "settled") return null; |
| 28 | const from = orderedIds.indexOf(movedId); |
| 29 | if (from < 0 && (typeof destination === "string" || destination.section === undefined)) |
| 30 | return null; |
| 31 | const result = orderedIds.filter((id) => id !== movedId); |
| 32 | let to: number; |
| 33 | if (typeof destination === "string") { |
| 34 | to = from + (destination === "up" ? -1 : 1); |
| 35 | if (to < 0 || to >= orderedIds.length) return null; |
| 36 | } else { |
| 37 | if (destination.targetId === null) { |
| 38 | if (destination.section === undefined) return null; |
| 39 | to = destination.placement === "before" ? 0 : result.length; |
| 40 | } else { |
| 41 | const target = result.indexOf(destination.targetId); |
| 42 | if (target < 0) return null; |
| 43 | to = target + (destination.placement === "after" ? 1 : 0); |
| 44 | } |
| 45 | } |
| 46 | if (to === from) return null; |
| 47 | result.splice(to, 0, movedId); |
| 48 | return result; |
| 49 | } |
| 50 | |
| 51 | export type OrderRow = Pick< |
| 52 | EnvironmentThreadShell, |
| 53 | | "id" |
| 54 | | "environmentId" |
| 55 | | "pinOrderKey" |
| 56 | | "activeOrderKey" |
| 57 | | "createdAt" |
| 58 | | "unsettledAt" |
| 59 | | "pinnedAt" |
| 60 | >; |
| 61 | |
| 62 | export interface PendingThreadOrder { |
| 63 | readonly section: "pinned" | "active"; |
| 64 | readonly orderedIds: readonly string[]; |
| 65 | readonly before: ReadonlyMap<string, { readonly key: string | null; readonly anchor: string }>; |
| 66 | readonly assignments: ReadonlyMap<string, string>; |
| 67 | readonly confirmed: ReadonlySet<string>; |
| 68 | readonly commandsComplete: boolean; |
| 69 | } |
| 70 | |
| 71 | function rowId(row: OrderRow): string { |
| 72 | return `${row.environmentId}:${row.id}`; |
| 73 | } |
| 74 | |
| 75 | function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) { |
| 76 | return { |
| 77 | key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null, |
| 78 | anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt), |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | export function createThreadMovePlanner(input: { |
| 83 | readonly ordered: readonly OrderRow[]; |
| 84 | readonly allThreads?: readonly OrderRow[]; |
| 85 | readonly section: PendingThreadOrder["section"]; |
| 86 | readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>; |
| 87 | }) { |
| 88 | const orderedIds = input.ordered.map(rowId); |
| 89 | const keysById = new Map( |
| 90 | (input.allThreads ?? input.ordered).map((row) => [ |
| 91 | rowId(row), |
| 92 | rowOrder(row, input.section).key, |
| 93 | ]), |
| 94 | ); |
| 95 | const writableIds = new Set( |
| 96 | (input.allThreads ?? input.ordered) |
| 97 | .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId)) |
| 98 | .map(rowId), |
| 99 | ); |
| 100 | return (movedId: string, direction: ThreadMoveDestination) => { |
| 101 | if (!writableIds.has(movedId)) return null; |
| 102 | const nextIds = threadOrderAfterMove(orderedIds, movedId, direction); |
| 103 | if (nextIds === null) return null; |
| 104 | const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId }); |
| 105 | return assignments === null || |
| 106 | assignments.length === 0 || |
| 107 | assignments.some((assignment) => !writableIds.has(assignment.id)) |
| 108 | ? null |
| 109 | : assignments; |
| 110 | }; |
| 111 | } |
| 112 | |
| 113 | export interface ThreadMoveAvailability { |
| 114 | readonly canMoveUp: boolean; |
| 115 | readonly canMoveDown: boolean; |
| 116 | } |
| 117 | |
| 118 | /** Compute per section; per-card planner probes make minute ticks quadratic. */ |
| 119 | export function computeThreadMoveAvailability(input: { |
| 120 | readonly ordered: readonly OrderRow[]; |
| 121 | readonly allThreads?: readonly OrderRow[]; |
| 122 | readonly section: PendingThreadOrder["section"]; |
| 123 | readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>; |
| 124 | readonly pendingOrder?: PendingThreadOrder | null; |
| 125 | }): Map<string, ThreadMoveAvailability> { |
| 126 | const result = new Map<string, ThreadMoveAvailability>(); |
| 127 | if (input.pendingOrder != null) return result; |
| 128 | const rows = input.ordered; |
| 129 | if (rows.length < 2) { |
| 130 | for (const row of rows) result.set(rowId(row), { canMoveUp: false, canMoveDown: false }); |
| 131 | return result; |
| 132 | } |
| 133 | const orderedIds: string[] = []; |
| 134 | const indexById = new Map<string, number>(); |
| 135 | for (const row of rows) { |
| 136 | const id = rowId(row); |
| 137 | indexById.set(id, orderedIds.length); |
| 138 | orderedIds.push(id); |
| 139 | } |
| 140 | const keysById = new Map<string, string | null>(); |
| 141 | const writableIds = new Set<string>(); |
| 142 | for (const row of input.allThreads ?? input.ordered) { |
| 143 | const id = rowId(row); |
| 144 | keysById.set(id, rowOrder(row, input.section).key); |
| 145 | if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id); |
| 146 | } |
| 147 | const reservedKeys = new Set<string>(); |
| 148 | keysById.forEach((key, id) => { |
| 149 | if (key != null && !indexById.has(id)) reservedKeys.add(key); |
| 150 | }); |
| 151 | // Swaps affect at most two positions; precomputed totals allow constant-size availability checks. |
| 152 | const midpoints = new Map<string, string | null>(); |
| 153 | const fastPathKey = (beforeKey: string | null, afterKey: string | null): string | null => { |
| 154 | const memoKey = `${beforeKey ?? ""}\u0000${afterKey ?? ""}`; |
| 155 | const cached = midpoints.get(memoKey); |
| 156 | if (cached !== undefined) return cached; |
| 157 | let key = pinOrderKeyBetween(beforeKey, afterKey); |
| 158 | while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey); |
| 159 | midpoints.set(memoKey, key); |
| 160 | return key; |
| 161 | }; |
| 162 | const spreadKeys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size) |
| 163 | .filter((key) => !reservedKeys.has(key)) |
| 164 | .slice(0, orderedIds.length); |
| 165 | const currentKeys = orderedIds.map((id) => keysById.get(id) ?? null); |
| 166 | const writableRow = orderedIds.map((id) => writableIds.has(id)); |
| 167 | let baselineWrites = 0; |
| 168 | let baselineUnwritableWrites = 0; |
| 169 | for (let position = 0; position < orderedIds.length; position += 1) { |
| 170 | if (currentKeys[position] === spreadKeys[position]) continue; |
| 171 | baselineWrites += 1; |
| 172 | if (!writableRow[position]) baselineUnwritableWrites += 1; |
| 173 | } |
| 174 | const rewriteViable = (index: number): boolean => { |
| 175 | let writes = baselineWrites; |
| 176 | let unwritableWrites = baselineUnwritableWrites; |
| 177 | for (const position of [index, index + 1]) { |
| 178 | const other = position === index ? index + 1 : index; |
| 179 | if (currentKeys[position] !== spreadKeys[position]) { |
| 180 | writes -= 1; |
| 181 | if (!writableRow[position]) unwritableWrites -= 1; |
| 182 | } |
| 183 | if (currentKeys[other] !== spreadKeys[position]) { |
| 184 | writes += 1; |
| 185 | if (!writableRow[other]) unwritableWrites += 1; |
| 186 | } |
| 187 | } |
| 188 | return writes > 0 && unwritableWrites === 0; |
| 189 | }; |
| 190 | for (const row of rows) { |
| 191 | const movedId = rowId(row); |
| 192 | const denied = { canMoveUp: false, canMoveDown: false }; |
| 193 | if (!writableIds.has(movedId)) { |
| 194 | result.set(movedId, denied); |
| 195 | continue; |
| 196 | } |
| 197 | const index = indexById.get(movedId); |
| 198 | if (index === undefined) { |
| 199 | result.set(movedId, denied); |
| 200 | continue; |
| 201 | } |
| 202 | const adjacentAvailable = (towardUp: boolean): boolean => { |
| 203 | const shifted = index + (towardUp ? -1 : 1); |
| 204 | if (shifted < 0 || shifted >= orderedIds.length) return false; |
| 205 | const beforeIndex = towardUp ? index - 2 : index + 1; |
| 206 | const afterIndex = towardUp ? index - 1 : index + 2; |
| 207 | const beforeId = beforeIndex < 0 ? null : (orderedIds[beforeIndex] ?? null); |
| 208 | const afterId = afterIndex >= orderedIds.length ? null : (orderedIds[afterIndex] ?? null); |
| 209 | const beforeKey = beforeId === null ? null : (keysById.get(beforeId) ?? null); |
| 210 | const afterKey = afterId === null ? null : (keysById.get(afterId) ?? null); |
| 211 | if ((beforeId === null || beforeKey != null) && (afterId === null || afterKey != null)) { |
| 212 | const key = fastPathKey(beforeKey, afterKey); |
| 213 | if (key !== null) return true; |
| 214 | } |
| 215 | return rewriteViable(Math.min(index, shifted)); |
| 216 | }; |
| 217 | result.set(movedId, { |
| 218 | canMoveUp: adjacentAvailable(true), |
| 219 | canMoveDown: adjacentAvailable(false), |
| 220 | }); |
| 221 | } |
| 222 | return result; |
| 223 | } |
| 224 | |
| 225 | export function createPendingThreadOrder(input: { |
| 226 | readonly section: PendingThreadOrder["section"]; |
| 227 | readonly ordered: readonly OrderRow[]; |
| 228 | readonly movedId: string; |
| 229 | readonly direction: ThreadMoveDestination; |
| 230 | readonly assignments: readonly { readonly id: string; readonly orderKey: string }[]; |
| 231 | }): PendingThreadOrder { |
| 232 | const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction); |
| 233 | if (orderedIds === null) throw new Error("Cannot begin an invalid thread move"); |
| 234 | return { |
| 235 | section: input.section, |
| 236 | orderedIds, |
| 237 | before: new Map(input.ordered.map((row) => [rowId(row), rowOrder(row, input.section)])), |
| 238 | assignments: new Map(input.assignments.map(({ id, orderKey }) => [id, orderKey])), |
| 239 | confirmed: new Set(), |
| 240 | commandsComplete: false, |
| 241 | }; |
| 242 | } |
| 243 | |
| 244 | /** Receipts and shell updates arrive independently. Only our own key writes |
| 245 | * may pass through the hold; membership and other arrangement changes win. */ |
| 246 | export function reconcilePendingThreadOrder( |
| 247 | pending: PendingThreadOrder, |
| 248 | ordered: readonly OrderRow[], |
| 249 | ): PendingThreadOrder | null { |
| 250 | if (ordered.length !== pending.before.size) return null; |
| 251 | const confirmed = new Set(pending.confirmed); |
| 252 | for (const row of ordered) { |
| 253 | const id = rowId(row); |
| 254 | const before = pending.before.get(id); |
| 255 | const current = rowOrder(row, pending.section); |
| 256 | if (before === undefined || current.anchor !== before.anchor) return null; |
| 257 | const assigned = pending.assignments.get(id); |
| 258 | if (assigned !== undefined && current.key === assigned) confirmed.add(id); |
| 259 | else if (current.key !== before.key || confirmed.has(id)) return null; |
| 260 | } |
| 261 | if (pending.commandsComplete && confirmed.size === pending.assignments.size) return null; |
| 262 | return confirmed.size === pending.confirmed.size ? pending : { ...pending, confirmed }; |
| 263 | } |
| 264 | |
| 265 | export function applyPendingThreadOrder<T extends OrderRow>( |
| 266 | rows: readonly T[], |
| 267 | section: PendingThreadOrder["section"], |
| 268 | pending: PendingThreadOrder | null | undefined, |
| 269 | ): T[] { |
| 270 | if (pending == null || pending.section !== section) return [...rows]; |
| 271 | const rank = new Map(pending.orderedIds.map((id, index) => [id, index])); |
| 272 | return [...rows].sort( |
| 273 | (left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity), |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | export function threadDropLifecycle( |
| 278 | thread: EnvironmentThreadShell, |
| 279 | section: "pinned" | "active", |
| 280 | now: string, |
| 281 | ) { |
| 282 | if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false }; |
| 283 | return { |
| 284 | pin: false, |
| 285 | unpin: thread.pinnedAt != null, |
| 286 | unsettle: thread.settledOverride === "settled", |
| 287 | unsnooze: effectiveSnoozed(thread, { now }), |
| 288 | }; |
| 289 | } |
| 290 | |
| 291 | export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled"; |
| 292 | |
| 293 | export function threadDragAction( |
| 294 | source: ThreadDragSection, |
| 295 | destination: ThreadDragSection, |
| 296 | resolve: MessageResolver = m, |
| 297 | ) { |
| 298 | if (destination === "snoozed") return null; |
| 299 | if (destination === "settled") |
| 300 | return source === "settled" |
| 301 | ? null |
| 302 | : resolve(msg("Settle", { $context: "verb, thread action" })); |
| 303 | if (source === destination) return resolve(msg("Reorder", { $context: "verb, thread action" })); |
| 304 | if (destination === "pinned") return resolve(msg("Pin", { $context: "verb, thread action" })); |
| 305 | if (source === "pinned") return resolve(msg("Unpin", { $context: "verb, thread action" })); |
| 306 | if (source === "settled") return resolve(msg("Unsettle", { $context: "verb, thread action" })); |
| 307 | return resolve(msg("Unsnooze", { $context: "verb, thread action" })); |
| 308 | } |