cruise 0.1.55

YAML-driven coding agent workflow orchestrator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import type { MutableRefObject } from "react";
import { getVersion } from "@tauri-apps/api/app";
import type { Update } from "../lib/updater";
import { checkForUpdate, checkForUpdateManual, downloadAndInstall } from "../lib/updater";
import { listSessions, cleanSessions, getUpdateReadiness } from "../lib/commands";
import type { Session, UpdateReadiness } from "../types";
import { PhaseBadge } from "./PhaseBadge";
import { Spinner } from "./Spinner";
import { formatLocalTime } from "../lib/format";
import { isApprovalReady } from "../lib/sessionActions";
import { ConfirmDialog } from "./ConfirmDialog";

type UpdateState = "available" | "downloading" | "error";

interface SessionSidebarProps {
  selectedId: string | null;
  onSelect: (session: Session) => void;
  onNewSession: () => void;
  onRunAll: () => void;
  /** When true, Run All is actively executing -- button is enabled regardless of pending sessions and shown in active state. */
  runAllActive?: boolean;
  onRefreshRef?: MutableRefObject<(() => void) | null>;
  /** Called after each load() when the currently selected session appears in
   *  the result, passing the latest DTO so the parent can stay in sync without
   *  triggering a view-change side effect (i.e. never call onSelect here). */
  onSelectedSessionUpdated?: (session: Session) => void;
  /** Session IDs that currently have a fix in progress; their rows show "Fixing" instead of "Awaiting Approval". */
  fixingSessionIds?: ReadonlySet<string>;
  /** Called after each successful load() when the fingerprint changes.
   *  App uses this to detect phase transitions (approval-ready, completed)
   *  and fire notifications without depending on the 3-second idle poll. */
  onSessionsChanged?: (sessions: Session[]) => void;
  /** Called when the user clicks the Settings button. */
  onSettings?: () => void;
  /** Wired to a function that immediately filters a session out of the local list (optimistic delete). */
  onOptimisticRemoveRef?: MutableRefObject<((id: string) => void) | null>;
}

export function SessionSidebar({ selectedId, onSelect, onNewSession, onRunAll, runAllActive, onRefreshRef, onSelectedSessionUpdated: onSelectedSessionUpdatedProp, onSessionsChanged: onSessionsChangedProp, fixingSessionIds, onSettings, onOptimisticRemoveRef }: SessionSidebarProps) {
  // Stable refs so load() can access the latest props without re-creating itself
  const onSelectedSessionUpdatedRef = useRef(onSelectedSessionUpdatedProp);
  const onSessionsChangedRef = useRef(onSessionsChangedProp);
  const selectedIdRef = useRef(selectedId);
  // Keep refs in sync with the latest props after every commit so that load()
  // (which captures these refs in its closure) never sees stale prop values.
  // Readers are effects and async callbacks — always post-commit — so the
  // post-render timing of useLayoutEffect is safe here.
  useLayoutEffect(() => {
    onSelectedSessionUpdatedRef.current = onSelectedSessionUpdatedProp;
    onSessionsChangedRef.current = onSessionsChangedProp;
    selectedIdRef.current = selectedId;
  });
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cleaning, setCleaning] = useState(false);
  const [cleanMessage, setCleanMessage] = useState<string | null>(null);
  const [version, setVersion] = useState<string | null>(null);
  const [update, setUpdate] = useState<Update | null>(null);
  const [updateState, setUpdateState] = useState<UpdateState>("available");
  const [updateReadiness, setUpdateReadiness] = useState<UpdateReadiness | null>(null);
  const [errorMsg, setErrorMsg] = useState("");
  const [manualCheck, setManualCheck] = useState<"idle" | "checking" | "upToDate" | { error: string }>("idle");
  const [runAllConfirmCount, setRunAllConfirmCount] = useState<number | null>(null);
  const lastFingerprintRef = useRef("");
  const inflightRef = useRef(false);

  const load = useCallback(async (silent = false) => {
    if (inflightRef.current) return;
    inflightRef.current = true;
    if (!silent) setLoading(true);
    try {
      const fetched = await listSessions();
      const sorted = [...fetched].sort((a, b) => {
        const aInput = a.awaitingInput || a.phase === "Awaiting Approval";
        const bInput = b.awaitingInput || b.phase === "Awaiting Approval";
        if (aInput !== bInput) return aInput ? -1 : 1;
        const aTime = a.updatedAt ?? a.createdAt;
        const bTime = b.updatedAt ?? b.createdAt;
        return bTime.localeCompare(aTime);
      });
      const fingerprint = sorted.map(s => `${s.id}:${s.phase}:${s.updatedAt ?? s.createdAt}:${!!s.awaitingInput}:${!!s.planAvailable}:${!!s.fixInProgress}`).join(",");
      if (fingerprint !== lastFingerprintRef.current) {
        lastFingerprintRef.current = fingerprint;
        setSessions(sorted);
        onSessionsChangedRef.current?.(sorted);
        if (selectedIdRef.current !== null) {
          const match = sorted.find((s) => s.id === selectedIdRef.current);
          if (match) {
            onSelectedSessionUpdatedRef.current?.(match);
          }
        }
      }
      setError(null);
    } catch (e) {
      if (!silent) {
        setError(String(e));
      }
    } finally {
      inflightRef.current = false;
      if (!silent) {
        setLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    // queueMicrotask defers load() past the current synchronous work so that
    // React Strict Mode's double-invocation of effects doesn't trigger two
    // concurrent list fetches: the first invocation starts load(), sets
    // inflightRef=true, then the effect cleanup runs and the second invocation
    // schedules a microtask — by that time inflightRef is already true and the
    // duplicate is dropped.
    queueMicrotask(() => void load());
  }, [load]);

  useEffect(() => {
    const doSilentLoad = () => {
      if (document.visibilityState === "visible") {
        void load(true);
      }
    };
    const interval = setInterval(doSilentLoad, 3000);
    document.addEventListener("visibilitychange", doSilentLoad);
    return () => {
      clearInterval(interval);
      document.removeEventListener("visibilitychange", doSilentLoad);
    };
  }, [load]);

  useEffect(() => {
    if (onRefreshRef) {
      onRefreshRef.current = () => void load(true);
      return () => { onRefreshRef.current = null; };
    }
  }, [load, onRefreshRef]);

  useEffect(() => {
    if (onOptimisticRemoveRef) {
      onOptimisticRemoveRef.current = (id: string) =>
        setSessions((prev) => prev.filter((s) => s.id !== id));
      return () => { onOptimisticRemoveRef.current = null; };
    }
  }, [onOptimisticRemoveRef]);

  useEffect(() => {
    let updateIntervalId: ReturnType<typeof setInterval>;

    void getVersion().then(setVersion).catch(() => {});

    void getUpdateReadiness().then(setUpdateReadiness).catch(() => {});

    const doCheck = () => {
      void checkForUpdate().then((u) => { if (u) setUpdate(u); });
    };

    const updateTimerId = setTimeout(() => {
      void getUpdateReadiness().then(setUpdateReadiness).catch(() => {});
      doCheck();
      updateIntervalId = setInterval(doCheck, 24 * 60 * 60 * 1000);
    }, 2000);

    return () => {
      clearTimeout(updateTimerId);
      clearInterval(updateIntervalId);
    };
  }, []);

  async function handleCheckUpdates() {
    setManualCheck("checking");
    try {
      const u = await checkForUpdateManual();
      if (u) {
        setUpdate(u);
        setManualCheck("idle");
      } else {
        setManualCheck("upToDate");
      }
    } catch (e) {
      setManualCheck({ error: String(e) });
    }
  }

  function handleDismissError() {
    setUpdate(null);
    setUpdateState("available");
    setErrorMsg("");
    setManualCheck("idle");
  }

  async function handleInstall() {
    setUpdateState("downloading");
    try {
      await downloadAndInstall(update!);
    } catch (e) {
      setUpdateState("error");
      setErrorMsg(String(e));
    }
  }

  async function handleClean() {
    setCleaning(true);
    setCleanMessage(null);
    try {
      const result = await cleanSessions();
      setCleanMessage(`${result.deleted} deleted (skipped: ${result.skipped})`);
      void load(true);
    } catch (e) {
      setCleanMessage(`Error: ${e}`);
    } finally {
      setCleaning(false);
    }
  }

  const showAutoUpdate = update && updateState === "available" && updateReadiness?.canAutoUpdate;
  const updateGuidance = updateReadiness && !updateReadiness.canAutoUpdate ? updateReadiness.guidance : null;
  const runnableCount = sessions.filter(
    (s) => s.phase === "Planned" || s.phase === "Suspended" || isApprovalReady(s),
  ).length;

  return (
    <div className="h-full flex flex-col">
      <div className="px-3 py-3 border-b border-gray-800 space-y-1.5">
        <div className="flex items-center justify-between gap-2">
          <h2 className="text-sm font-semibold text-gray-200">Sessions</h2>
          <div className="flex items-center gap-1">
            <button
              type="button"
              onClick={() => void handleClean()}
              disabled={cleaning}
              className="px-2 py-1 text-xs text-gray-400 hover:text-gray-200 hover:bg-gray-800 rounded disabled:opacity-50 flex items-center gap-1"
              title="Clean completed sessions"
            >
              {cleaning ? (
                <>
                  <Spinner />
                  Cleaning...
                </>
              ) : (
                "Clean"
              )}
            </button>
            <button
              type="button"
              onClick={() => {
                if (runAllActive) {
                  onRunAll();
                } else {
                  setRunAllConfirmCount(runnableCount);
                }
              }}
              disabled={!runAllActive && runnableCount === 0}
              className={`px-2 py-1 text-xs rounded ${
                runAllActive
                  ? "bg-blue-600 text-white hover:bg-blue-700"
                  : "text-gray-400 hover:text-gray-200 hover:bg-gray-800 disabled:opacity-50"
              }`}
              aria-label={runAllActive ? "View running sessions" : "Run all pending sessions"}
              title={runAllActive ? "View running sessions" : "Run all pending sessions"}
            >
              Run All
            </button>
            <button
              type="button"
              onClick={onNewSession}
              className="px-2 py-1 text-xs bg-blue-600 text-white hover:bg-blue-700 rounded"
            >
              + New
            </button>
            {onSettings && (
              <button
                type="button"
                onClick={onSettings}
                aria-label="Settings"
                title="Settings"
                className="px-2 py-1 text-xs text-gray-400 hover:text-gray-200 hover:bg-gray-800 rounded"
              >
                {'\u2699'}
              </button>
            )}
          </div>
        </div>
        {cleanMessage && (
          <p className="text-xs text-gray-400">{cleanMessage}</p>
        )}
      </div>

      <div className="flex-1 overflow-y-auto">
        {loading && (
          <p className="p-3 text-xs text-gray-500">Loading...</p>
        )}
        {error && (
          <p className="p-3 text-xs text-red-400">Error: {error}</p>
        )}
        {!loading && !error && sessions.length === 0 && (
          <p className="p-3 text-xs text-gray-500">No sessions found.</p>
        )}
        {sessions.map((s) => (
          <button
            key={s.id}
            type="button"
            onClick={() => onSelect(s)}
            className={`w-full text-left px-3 py-2.5 border-b border-gray-800/50 hover:bg-gray-800 transition-colors ${
              selectedId === s.id ? "bg-gray-800" : ""
            }`}
          >
            <div className="flex items-center justify-between gap-2 mb-0.5">
              <span className="text-xs text-gray-500 font-mono truncate">{s.id}</span>
              <PhaseBadge phase={s.phase} planAvailable={s.planAvailable} fixing={fixingSessionIds?.has(s.id) || !!s.fixInProgress} />
            </div>
            <p className="text-sm text-gray-300 truncate">{s.title || s.input}</p>
            {s.title && (
              <p className="text-xs text-gray-500 truncate">{s.input}</p>
            )}
            <div className="flex items-center gap-1.5 mt-0.5">
              <span className="text-xs text-blue-400/70 font-mono truncate">
                {s.baseDir.replace(/\\/g, "/").split("/").filter(Boolean).at(-1) ?? s.baseDir}
              </span>
              <span className="text-xs text-gray-600">{formatLocalTime(s.updatedAt ?? s.createdAt)}</span>
            </div>
          </button>
        ))}
      </div>

      {/* Sidebar footer: version & update */}
      <div className="flex-shrink-0 border-t border-gray-800 px-3 py-2">
        <div className="text-xs text-gray-500">{version ? `v${version}` : "..."}</div>
        {showAutoUpdate && (
          <div className="mt-1 space-y-1">
            <div className="text-xs text-green-400">v{update.version} available</div>
            <button
              type="button"
              onClick={() => void handleInstall()}
              className="px-2 py-0.5 bg-blue-600 text-white rounded text-xs hover:bg-blue-700"
            >
              Update
            </button>
          </div>
        )}
        {updateGuidance && (
          <div className="mt-1 text-xs text-yellow-400">{updateGuidance}</div>
        )}
        {updateState === "downloading" && (
          <div className="mt-1 text-xs text-gray-400">Downloading...</div>
        )}
        {updateState === "error" && (
          <div className="mt-1 space-y-1">
            <div className="text-xs text-red-400">{errorMsg}</div>
            <button
              type="button"
              onClick={handleDismissError}
              className="px-2 py-0.5 border border-gray-700 text-gray-400 rounded text-xs hover:bg-gray-800"
            >
              Dismiss
            </button>
          </div>
        )}
        <div className="mt-1">
          {manualCheck === "checking" ? (
            <div className="text-xs text-gray-400">Checking...</div>
          ) : (
            <button
              type="button"
              onClick={() => void handleCheckUpdates()}
              className="px-2 py-0.5 border border-gray-700 text-gray-400 rounded text-xs hover:bg-gray-800"
            >
              Check Updates
            </button>
          )}
          {manualCheck === "upToDate" && !update && (
            <div className="mt-0.5 text-xs text-gray-400">Up to date</div>
          )}
          {typeof manualCheck === "object" && (
            <div className="mt-0.5 space-y-1">
              <div className="text-xs text-red-400">{manualCheck.error}</div>
              <button
                type="button"
                onClick={() => setManualCheck("idle")}
                className="px-2 py-0.5 border border-gray-700 text-gray-400 rounded text-xs hover:bg-gray-800"
              >
                Dismiss
              </button>
            </div>
          )}
        </div>
      </div>
      {runAllConfirmCount !== null && (
        <ConfirmDialog
          title="Run All Sessions"
          message={`Run ${runAllConfirmCount} pending session(s) in parallel? Already-completed sessions will be skipped.`}
          confirmLabel="Run All"
          variant="primary"
          onConfirm={() => {
            setRunAllConfirmCount(null);
            onRunAll();
          }}
          onCancel={() => setRunAllConfirmCount(null)}
        />
      )}
    </div>
  );
}