Compare commits

...
Author SHA1 Message Date
Theo Browne 19b837ee9c feat(server): sync thread read status across clients 2026-08-13 16:23:03 -07:00
Theo Browne db1507e986 feat: allow disabling auto-settle on merge (#5880) 2026-08-13 16:18:15 -07:00
Rakshith Bhat 96bfa67b3d fix(web): align the snoozed thread wake icon (#6215) 2026-08-13 18:14:24 -04:00
Taylor Bombay 5ff3a03ada fix(web): align sidebar wordmark label (#6086) 2026-08-13 18:14:13 -04:00
t3-code[bot]andmaria 23d45d914e fix(web): restore default stage artwork colors (#6535)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-13 18:04:24 -04:00
Paul van DykandClaude Opus 5 bad1143b02 fix(mobile): show a real settings cog in the Android sidebar header (#6520)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-13 20:41:17 +00:00
Adamulek123andJulius Marminge 92d4a2e996 fix(web): scope pull request errors to their environment (#6490)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 20:40:21 +00:00
Utkarsh Patil 2fab18e289 fix(web): show unlinked icon when viewport aspect ratio is unlocked (#6509) 2026-08-13 16:03:48 -04:00
1b16ed663f fix(web): avoid Clerk close button overlap (#6442)
Co-authored-by: t3-code[bot] <236186684+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-13 15:08:28 -04:00
SimoneandSimone 83ad26c3a3 fix(mobile): prevent invalid HTML entities from crashing markdown (#6495)
Co-authored-by: Simone <[email protected]>
2026-08-13 15:08:13 -04:00
Chris Deeming fd51561b4e fix(mobile): extend blockquotes across wrapped lines (#6482) 2026-08-13 20:00:03 +02:00
Julius Marminge 9e201941aa Remove rebase requirement before opening PR (#6479) 2026-08-13 15:04:42 +00:00
t3-code[bot]andJulius Marminge 2ab188f1c0 fix: ignore pull request actions in latency tracker (#6476)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 14:51:31 +00:00
maria 9513e62e24 Add bil0000 to VOUCHED contributors list (#6462) 2026-08-13 14:26:36 +00:00
Bilal Bakr 97db94c9bf fix(web): keep pull request panel within viewport (#6451) 2026-08-13 08:45:33 -04:00
Exotic 5015d7cf9f fix(web): keep turn minimap stable as composer grows (#6414) 2026-08-13 15:30:37 +05:30
Nick Anisimov df19f6cfe3 fix(server): align Codex collaboration prompts (#6432) 2026-08-13 10:31:53 +02:00
Dominic RoyandClaude Fable 5 6bc6cb6be4 fix(web): keep diff file lists scrollable past expanded files (#6423)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 20:11:53 -07:00
Theo BrowneandClaude Fable 5 1e59b4c400 fix(web): keep the typed prompt when a draft changes repo (#6393)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 16:26:27 -07:00
t3-code[bot]andUtkarsh Patil 33f9705926 fix(web): make reset zoom hover visible (#6385)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 19:13:35 -04:00
Dominic Roy da6253b3dd web/settings: fix source control scan on relay environments (#6230) 2026-08-12 16:13:06 -07:00
90 changed files with 1685 additions and 616 deletions

No files matched your search

+1
View File
@@ -38,3 +38,4 @@ github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
github:bil0000
-1
View File
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
- UI changes need before/after images. Motion or timing needs a short video.
- One concern per PR. If the description says "also", split it.
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
@@ -32,6 +32,7 @@ const clientSettings: ClientSettings = {
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import { CopyTextButton } from "./CopyTextButton";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
} from "./nativeMarkdownText";
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
import type {
MarkdownCodeHighlighter,
MarkdownHighlightedToken,
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
} from "./SelectableMarkdownText.types";
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -359,7 +358,7 @@ function NativeTable(props: {
}}
>
<NativeMarkdownSelectableText
runs={nativeMarkdownTextRuns(cell).map((run) =>
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
@@ -376,6 +375,7 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
<NativeMarkdownImage
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
<SelectableNode
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
function NativeList(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
@@ -534,6 +539,7 @@ function NativeList(props: {
<NativeMarkdownBlock
key={nodeKey(child, childIndex)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -551,6 +557,7 @@ function NativeList(props: {
export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeTable
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeMarkdownImage
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeList
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
>
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
chunk.kind === "rich" ? (
<NativeMarkdownBlock
node={chunk.node}
skills={skills}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
function decodeCodePoint(codePoint: number, entity: string): string {
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
return entity;
}
return String.fromCodePoint(codePoint);
}
function decodeHtmlEntitiesOnce(value: string): string {
return value.replace(
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
if (decimal) {
return String.fromCodePoint(Number.parseInt(decimal, 10));
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
}
if (hexadecimal) {
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
}
switch (entity.toLowerCase()) {
case "&amp;":
@@ -661,6 +668,7 @@ function appendDocumentBlock(
function containsRichBlock(node: MarkdownNode): boolean {
if (
node.type === "code_block" ||
node.type === "blockquote" ||
node.type === "table" ||
node.type === "image" ||
node.type === "horizontal_rule" ||
@@ -1,97 +0,0 @@
package expo.modules.t3nativecontrols
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
private val iconView = HeaderIconView(context)
private val onTriggered by EventDispatcher()
init {
isClickable = true
isFocusable = true
setOnClickListener {
onTriggered(emptyMap<String, Any>())
}
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
fun setLabel(label: String) {
contentDescription = label
}
fun setSystemImage(systemImage: String) {
iconView.systemImage = systemImage
}
}
private class HeaderIconView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#6B7280")
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
strokeWidth = 3f * resources.displayMetrics.density
style = Paint.Style.STROKE
}
var systemImage: String = "gearshape"
set(value) {
field = value
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
val size = minOf(width, height).toFloat()
if (systemImage == "square.and.pencil") {
drawNewTask(canvas, cx, cy, size)
} else {
drawSettings(canvas, cx, cy, size)
}
}
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val radius = size * 0.12f
canvas.drawCircle(cx, cy, radius, paint)
for (index in 0 until 8) {
val angle = Math.PI * index / 4.0
val inner = size * 0.19f
val outer = size * 0.27f
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
canvas.drawLine(sx, sy, ex, ey, paint)
}
}
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val left = cx - size * 0.2f
val top = cy - size * 0.16f
val right = cx + size * 0.14f
val bottom = cy + size * 0.2f
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
canvas.drawLine(
cx - size * 0.02f,
cy + size * 0.13f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
canvas.drawLine(
cx + size * 0.17f,
cy - size * 0.2f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
}
}
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
?.resolve("t3-showcase-ready")
?.writeText(scene)
}
View(T3HeaderButtonView::class) {
Prop("label") { view: T3HeaderButtonView, label: String ->
view.setLabel(label)
}
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -1,62 +0,0 @@
import ExpoModulesCore
import UIKit
public final class T3HeaderButtonView: ExpoView {
private static let size: CGFloat = 44
private static let symbolSize: CGFloat = 18
private let button = UIButton(type: .system)
private var systemImage = "circle"
let onTriggered = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isAccessibilityElement = false
button.frame = bounds
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
addSubview(button)
applyConfiguration()
}
public override var intrinsicContentSize: CGSize {
CGSize(width: Self.size, height: Self.size)
}
public func setLabel(_ label: String) {
button.accessibilityLabel = label
}
public func setSystemImage(_ systemImage: String) {
guard self.systemImage != systemImage else {
return
}
self.systemImage = systemImage
applyConfiguration()
}
private func applyConfiguration() {
var configuration: UIButton.Configuration
if #available(iOS 26.0, *) {
configuration = .glass()
configuration.cornerStyle = .capsule
} else {
configuration = .plain()
}
configuration.baseForegroundColor = .label
configuration.contentInsets = .zero
configuration.image = UIImage(systemName: systemImage)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
pointSize: Self.symbolSize,
weight: .regular
)
button.configuration = configuration
}
@objc private func handlePress() {
onTriggered()
}
}
@@ -87,16 +87,5 @@ public final class T3NativeControlsModule: Module {
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
}
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
}
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
+7 -2
View File
@@ -207,6 +207,9 @@ export function HomeScreen(props: HomeScreenProps) {
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
@@ -483,8 +486,8 @@ export function HomeScreen(props: HomeScreenProps) {
// Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or
// optimistic holds.
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
// closed PR auto-settles its thread on the next partition (mirrors web).
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule, matching web.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -665,6 +668,7 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -676,6 +680,7 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
@@ -522,9 +522,21 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
return (
<SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
<SettingsSwitchRow
icon="arrow.triangle.branch"
label="Auto-settle merged threads"
value={autoSettleOnMerge}
onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}
/>
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
</SettingsSection>
);
@@ -10,6 +10,7 @@ import {
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
@@ -29,6 +30,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
@@ -214,6 +216,10 @@ function ThreadNavigationSidebarPane(
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -411,8 +417,8 @@ function ThreadNavigationSidebarPane(
// Thread List v2 (beta) support — same model as the compact Home list
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
// PR states stream in per-row; merged/closed PRs auto-settle their thread
// on the next partition.
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -546,6 +552,7 @@ function ThreadNavigationSidebarPane(
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -557,6 +564,7 @@ function ThreadNavigationSidebarPane(
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
@@ -63,6 +63,7 @@ import { useSelectedThreadRequests } from "../../state/use-selected-thread-reque
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { useEnvironmentServerConfig } from "../../state/entities";
import { projectThreadContentPresentation } from "./threadContentPresentation";
import {
useAdaptiveWorkspaceLayout,
@@ -214,6 +215,33 @@ function ThreadRouteContent(
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const markThreadViewed = useAtomCommand(threadEnvironment.markViewed, { reportFailure: false });
const selectedServerConfig = useEnvironmentServerConfig(selectedThread?.environmentId ?? null);
useFocusEffect(
useCallback(() => {
const thread = selectedThread;
const completedAt = thread?.latestTurn?.completedAt;
if (
thread == null ||
completedAt == null ||
selectedServerConfig?.environment.capabilities.threadViewStatus !== true
)
return;
void markThreadViewed({
environmentId: thread.environmentId,
input: {
threadId: thread.id,
viewedAt: completedAt,
},
});
}, [
markThreadViewed,
selectedServerConfig?.environment.capabilities.threadViewStatus,
selectedThread?.environmentId,
selectedThread?.id,
selectedThread?.latestTurn?.completedAt,
]),
);
const navigation = useNavigation();
const params = props.route.params;
const environmentIdRaw = firstRouteParam(params.environmentId);
@@ -1,16 +0,0 @@
import { View } from "react-native";
import { T3HeaderButton } from "../../native/T3HeaderButton.android";
import type { SidebarHeaderActionsProps } from "./sidebar-header-actions";
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
return (
<View className="h-11 flex-row gap-1">
<T3HeaderButton
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
/>
</View>
);
}
@@ -369,8 +369,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
merged/closed work (mirrors web's onChangeRequestState). */
/** Reports this row's live PR state for the partition's merge and close
rules. Mirrors web's onChangeRequestState. */
readonly onChangeRequestState?: (
threadKey: string,
state: "open" | "closed" | "merged" | null,
@@ -263,6 +263,21 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("keeps a merged thread active when auto-settle on merge is off", () => {
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
const layout = buildThreadListV2Items({
threads: [merged],
environmentId: null,
searchQuery: "",
changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
autoSettleOnMerge: false,
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["merged"]);
expect(layout.settledCount).toBe(0);
});
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -306,9 +306,8 @@ export function buildThreadListV2ListItems(input: {
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
* the default is fixed here rather than user-configurable.
* the settled recency tail, matching the web v2 list. Mobile stores these
* auto-settle preferences per device.
*/
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -329,6 +328,7 @@ export function buildThreadListV2Items(input: {
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
readonly autoSettleOnMerge?: boolean;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
@@ -349,6 +349,7 @@ export function buildThreadListV2Items(input: {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
@@ -405,7 +406,12 @@ export function buildThreadListV2Items(input: {
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread);
} else {
+69 -1
View File
@@ -126,6 +126,22 @@ describe("nativeMarkdownTextRuns", () => {
]);
});
it.each([
["&#128512;", "😀"],
["&#x1f680;", "🚀"],
["&#9999999999;", "&#9999999999;"],
["&#x110000;", "&#x110000;"],
["&amp;#9999999999;", "&#9999999999;"],
["&amp;#x110000;", "&#x110000;"],
])("normalizes numeric entity %s without throwing", (content, expected) => {
const node: MarkdownNode = {
type: "paragraph",
children: [{ type: "text", content }],
};
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: expected }]);
});
it("reads inline content from nested text nodes", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -173,6 +189,25 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("decorates known skill references inside blockquotes", () => {
const node: MarkdownNode = {
type: "blockquote",
children: [
{
type: "paragraph",
children: [{ type: "text", content: "Use $ui for this." }],
},
],
};
expect(nativeMarkdownDocumentRuns(node, [{ name: "ui", displayName: "UI" }])).toContainEqual({
text: "$ui",
role: "body",
skillName: "ui",
skillLabel: "UI",
});
});
it("leaves unknown skill-like text unchanged", () => {
const node: MarkdownNode = {
type: "document",
@@ -328,7 +363,7 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("includes quotes and fenced code in the same selectable string", () => {
it("preserves quotes and fenced code in document runs", () => {
const node: MarkdownNode = {
type: "document",
children: [
@@ -414,6 +449,39 @@ describe("nativeMarkdownListItemBlocks", () => {
});
describe("nativeMarkdownDocumentChunks", () => {
it("renders plain blockquotes as rich blocks so their marker spans wrapped lines", () => {
const blockquote: MarkdownNode = {
type: "blockquote",
beg: 0,
end: 120,
children: [
{
type: "paragraph",
children: [
{
type: "text",
content:
"Persistent random per-result keys are the strongest design, even when this text wraps.",
},
],
},
],
};
expect(
nativeMarkdownDocumentChunks({
type: "document",
children: [blockquote],
}),
).toEqual([
{
kind: "rich",
key: "rich:blockquote:0:120",
node: blockquote,
},
]);
});
it("keeps headings and plain lists in one selectable document", () => {
const document: MarkdownNode = {
type: "document",
@@ -1,26 +0,0 @@
import { requireNativeView } from "expo";
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
interface NativeHeaderButtonProps extends ViewProps {
readonly label: string;
readonly systemImage: "gearshape" | "square.and.pencil";
readonly onTriggered: (event: NativeSyntheticEvent<Record<string, never>>) => void;
}
const NativeHeaderButton = requireNativeView<NativeHeaderButtonProps>("T3NativeControls");
export function T3HeaderButton(props: {
readonly accessibilityLabel: string;
readonly icon: NativeHeaderButtonProps["systemImage"];
readonly onPress: () => void;
readonly style?: StyleProp<ViewStyle>;
}) {
return (
<NativeHeaderButton
label={props.accessibilityLabel}
onTriggered={props.onPress}
style={[{ width: 44, height: 44 }, props.style]}
systemImage={props.icon}
/>
);
}
@@ -26,6 +26,7 @@ export interface Preferences {
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
readonly autoSettleOnMerge?: boolean;
/**
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into
@@ -85,6 +86,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
autoSettleOnMerge?: boolean;
legacyThreadListEnabled?: boolean;
} = {};
@@ -122,6 +124,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.autoSettleOnMerge === "boolean") {
preferences.autoSettleOnMerge = parsed.autoSettleOnMerge;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
}
+3 -1
View File
@@ -15,7 +15,6 @@ import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
import { environmentSnapshotAtom } from "./shell";
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime);
export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
environmentThreads.stateAtom,
@@ -24,6 +23,9 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: environmentSnapshotAtom,
});
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime, {
threadShellAtom: environmentThreadShells.threadShellAtom,
});
const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
Atom.withLabel("mobile-environment-thread:empty"),
@@ -148,6 +148,7 @@ export const make = Effect.gen(function* () {
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadViewStatus: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
@@ -237,6 +237,40 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
yield* eventStore.append({
type: "thread.view-status-updated",
eventId: EventId.make("evt-viewed-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:03.000Z",
commandId: CommandId.make("cmd-viewed-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-viewed-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
lastViewedAt: "2026-01-01T00:00:03.000Z",
},
});
yield* projectionPipeline.bootstrap;
const viewRows = yield* sql<{
readonly lastViewedAt: string | null;
readonly updatedAt: string;
}>`
SELECT
last_viewed_at AS "lastViewedAt",
updated_at AS "updatedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(viewRows, [
{
lastViewedAt: "2026-01-01T00:00:03.000Z",
updatedAt: "2026-01-01T00:00:02.000Z",
},
]);
}),
);
});
@@ -617,6 +617,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: event.payload.lastViewedAt ?? null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
@@ -663,6 +664,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.view-status-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) return;
yield* projectionThreadRepository.upsert({
...existingRow.value,
lastViewedAt: event.payload.lastViewedAt,
});
return;
}
case "thread.settled": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -321,6 +321,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -440,6 +441,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -424,6 +424,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -460,6 +461,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -498,6 +500,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -940,6 +943,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -1573,6 +1577,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
lastViewedAt: row.lastViewedAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1780,6 +1785,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
lastViewedAt: row.lastViewedAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1916,6 +1922,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
lastViewedAt: row.lastViewedAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2061,6 +2068,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
lastViewedAt: row.lastViewedAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2340,6 +2348,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
lastViewedAt: threadRow.value.lastViewedAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
@@ -2461,6 +2470,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
lastViewedAt: threadRow.value.lastViewedAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
+2
View File
@@ -10,6 +10,7 @@ import {
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadViewStatusUpdatedPayload as ContractsThreadViewStatusUpdatedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
@@ -42,6 +43,7 @@ export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadS
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadViewStatusUpdatedPayload = ContractsThreadViewStatusUpdatedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
+63
View File
@@ -377,6 +377,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
interactionMode: command.interactionMode,
branch: command.branch,
worktreePath: command.worktreePath,
lastViewedAt: command.createdAt,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
@@ -450,6 +451,68 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.mark-viewed": {
const thread = yield* requireThread({ readModel, command, threadId: command.threadId });
const previousViewedAt = thread.lastViewedAt ?? null;
if (
previousViewedAt !== command.expectedLastViewedAt &&
previousViewedAt !== command.supersededViewedAt
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} view status changed after this view was queued`,
});
}
const occurredAt = yield* nowIso;
const lastViewedAt =
previousViewedAt != null && Date.parse(previousViewedAt) > Date.parse(command.viewedAt)
? previousViewedAt
: command.viewedAt;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.view-status-updated",
payload: { threadId: command.threadId, lastViewedAt },
};
}
case "thread.mark-unread": {
const thread = yield* requireThread({ readModel, command, threadId: command.threadId });
const completedAt = thread.latestTurn?.completedAt;
if (completedAt == null) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has no completed turn to mark unread`,
});
}
const occurredAt = yield* nowIso;
const previousViewedAt = thread.lastViewedAt;
// Repeated unread actions still move the optimistic view token.
const unreadFrom =
previousViewedAt != null && Date.parse(previousViewedAt) < Date.parse(completedAt)
? previousViewedAt
: completedAt;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.view-status-updated",
payload: {
threadId: command.threadId,
lastViewedAt: DateTime.formatIso(
DateTime.subtract(DateTime.makeUnsafe(unreadFrom), { milliseconds: 1 }),
),
},
};
}
case "thread.settle": {
const thread = yield* requireThreadNotArchived({
readModel,
@@ -0,0 +1,228 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const COMPLETED_AT = "1970-01-01T00:00:00.000Z";
function makeReadModel(completedAt: string | null = COMPLETED_AT): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: COMPLETED_AT,
startedAt: COMPLETED_AT,
completedAt,
assistantMessageId: null,
},
createdAt: COMPLETED_AT,
updatedAt: COMPLETED_AT,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: COMPLETED_AT,
};
}
it.layer(NodeServices.layer)("thread view-status decider", (it) => {
it.effect("uses server-owned timestamps when a thread is viewed", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-viewed",
commandId: CommandId.make("cmd-viewed"),
threadId: ThreadId.make("thread-1"),
viewedAt: COMPLETED_AT,
expectedLastViewedAt: null,
supersededViewedAt: null,
},
readModel: makeReadModel(),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.view-status-updated");
if (events[0]?.type === "thread.view-status-updated") {
expect(events[0].payload.lastViewedAt).toBe(COMPLETED_AT);
expect(Number.isFinite(Date.parse(events[0].payload.lastViewedAt))).toBe(true);
}
}),
);
it.effect("marks unread immediately before the latest server completion", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-unread",
commandId: CommandId.make("cmd-unread"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.view-status-updated");
if (events[0]?.type === "thread.view-status-updated") {
expect(events[0].payload.lastViewedAt).toBe("1969-12-31T23:59:59.999Z");
}
}),
);
it.effect("accepts a server-owned boundary ahead of the decider clock", () =>
Effect.gen(function* () {
const viewedAt = "1970-01-01T00:00:00.001Z";
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-viewed",
commandId: CommandId.make("cmd-viewed-clock-skew"),
threadId: ThreadId.make("thread-1"),
viewedAt,
expectedLastViewedAt: null,
supersededViewedAt: null,
},
readModel: makeReadModel(),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.view-status-updated");
if (events[0]?.type === "thread.view-status-updated") {
expect(events[0].payload.lastViewedAt).toBe(viewedAt);
}
}),
);
it.effect("does not move viewed state backwards", () =>
Effect.gen(function* () {
const readModel = makeReadModel();
const previousViewedAt = "1970-01-01T00:00:10.000Z";
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-viewed",
commandId: CommandId.make("cmd-viewed-stale"),
threadId: ThreadId.make("thread-1"),
viewedAt: "1970-01-01T00:00:05.000Z",
expectedLastViewedAt: previousViewedAt,
supersededViewedAt: null,
},
readModel: {
...readModel,
threads: [{ ...readModel.threads[0]!, lastViewedAt: previousViewedAt }],
},
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.view-status-updated");
if (events[0]?.type === "thread.view-status-updated") {
expect(events[0].payload.lastViewedAt).toBe(previousViewedAt);
}
}),
);
it.effect("does not let a queued view undo a newer unread action", () =>
Effect.gen(function* () {
const readModel = makeReadModel();
const unreadEvent = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-unread",
commandId: CommandId.make("cmd-unread-before-stale-view"),
threadId: ThreadId.make("thread-1"),
},
readModel,
});
const unreadEvents = Array.isArray(unreadEvent) ? unreadEvent : [unreadEvent];
expect(unreadEvents[0]?.type).toBe("thread.view-status-updated");
if (unreadEvents[0]?.type !== "thread.view-status-updated") return;
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-viewed",
commandId: CommandId.make("cmd-viewed-queued-before-unread"),
threadId: ThreadId.make("thread-1"),
viewedAt: COMPLETED_AT,
expectedLastViewedAt: null,
supersededViewedAt: null,
},
readModel: {
...readModel,
threads: [
{
...readModel.threads[0]!,
lastViewedAt: unreadEvents[0].payload.lastViewedAt,
},
],
},
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("accepts a view that follows its queued predecessor", () =>
Effect.gen(function* () {
const readModel = makeReadModel();
const predecessorViewedAt = "1970-01-01T00:00:05.000Z";
const viewedAt = "1970-01-01T00:00:10.000Z";
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-viewed",
commandId: CommandId.make("cmd-viewed-after-predecessor"),
threadId: ThreadId.make("thread-1"),
viewedAt,
expectedLastViewedAt: null,
supersededViewedAt: predecessorViewedAt,
},
readModel: {
...readModel,
threads: [{ ...readModel.threads[0]!, lastViewedAt: predecessorViewedAt }],
},
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.view-status-updated");
if (events[0]?.type === "thread.view-status-updated") {
expect(events[0].payload.lastViewedAt).toBe(viewedAt);
}
}),
);
it.effect("rejects mark-unread before any turn completes", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-unread",
commandId: CommandId.make("cmd-unread-empty"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(null),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
@@ -91,6 +91,7 @@ describe("orchestration projector", () => {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
@@ -30,6 +30,7 @@ import {
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadViewStatusUpdatedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -303,6 +304,7 @@ export function projectEvent(
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: payload.lastViewedAt ?? null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
@@ -357,6 +359,21 @@ export function projectEvent(
})),
);
case "thread.view-status-updated":
return decodeForEvent(
ThreadViewStatusUpdatedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
lastViewedAt: payload.lastViewedAt,
}),
})),
);
case "thread.settled":
return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -94,6 +94,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
@@ -157,6 +158,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: "settled",
settledAt: "2026-03-25T00:00:00.000Z",
lastViewedAt: "2026-03-25T01:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
pinnedAt: "2026-03-25T00:00:00.000Z",
@@ -45,6 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at,
settled_override,
settled_at,
last_viewed_at,
snoozed_until,
snoozed_at,
pinned_at,
@@ -72,6 +73,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.lastViewedAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
@@ -99,6 +101,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
last_viewed_at = excluded.last_viewed_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
@@ -133,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -169,6 +173,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
last_viewed_at AS "lastViewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -53,6 +53,7 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
import Migration0041 from "./Migrations/041_ProjectionThreadsLastViewedAt.ts";
/**
* Migration loader with all migrations defined inline.
@@ -105,6 +106,7 @@ export const migrationEntries = [
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
[40, "ProjectionProjectFaviconPath", Migration0040],
[41, "ProjectionThreadsLastViewedAt", Migration0041],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,49 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("041_ProjectionThreadsLastViewedAt", (it) => {
it.effect("starts existing threads read at the upgrade boundary", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 40 });
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
created_at,
updated_at
)
VALUES (
'thread-1',
'project-1',
'Thread 1',
'{"provider":"codex","model":"gpt-5.4"}',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 41 });
const rows = yield* sql<{ readonly lastViewedAt: string | null }>`
SELECT last_viewed_at AS "lastViewedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.strictEqual(rows.length, 1);
assert.ok(rows[0]?.lastViewedAt != null);
assert.ok(Number.isFinite(Date.parse(rows[0].lastViewedAt)));
assert.ok(rows[0].lastViewedAt > "2026-01-01T00:00:00.000Z");
}),
);
});
@@ -0,0 +1,22 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "last_viewed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN last_viewed_at TEXT
`;
// Existing threads start read, while wakes after the upgrade remain visible.
yield* sql`
UPDATE projection_threads
SET last_viewed_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
`;
}
});
@@ -39,6 +39,7 @@ export const ProjectionThread = Schema.Struct({
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
lastViewedAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
@@ -120,7 +120,7 @@ Example:
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include:
* A clear title
* A brief summary section
@@ -128,9 +128,17 @@ plan content should be human and agent digestible. The final plan must be plan-o
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes.
Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes.
Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand.
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
If the user stays in Plan mode and asks for revisions after a prior \`<proposed_plan>\`, any new \`<proposed_plan>\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`<proposed_plan>\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`<proposed_plan>\` unchanged.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
</collaboration_mode>`;
@@ -142,7 +150,7 @@ Your active mode changes only when new developer instructions with a different \
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
Use the \`request_user_input\` tool only when it is listed in the available tools for this turn.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
@@ -7,7 +7,7 @@ import {
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
import { Link2, X } from "lucide-react";
import { Link2, Unlink2, X } from "lucide-react";
import { useState } from "react";
import { Button } from "~/components/ui/button";
@@ -310,7 +310,11 @@ export function BrowserDeviceToolbar({
onPointerDown={(event) => event.preventDefault()}
onClick={toggleAspectRatio}
>
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
{aspectRatio === null ? (
<Unlink2 className={cn(aspectRatio !== null && "text-foreground")} />
) : (
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
)}
</Button>
<Button
variant="ghost"
+57 -33
View File
@@ -27,6 +27,7 @@ import {
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import {
changeRequestAutoSettles,
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
@@ -100,7 +101,6 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -239,6 +239,7 @@ import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import {
useProject,
useProjects,
useServerConfigs,
useThread,
useThreadRefs,
useThreadShell,
@@ -273,6 +274,7 @@ import {
ThreadErrorBanner,
} from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { hasUnseenWake } from "./Sidebar.logic";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import {
@@ -1215,6 +1217,9 @@ function ChatViewContent(props: ChatViewProps) {
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const markThreadViewed = useAtomCommand(threadEnvironment.markViewed, {
reportFailure: false,
});
const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
@@ -1238,6 +1243,7 @@ function ChatViewContent(props: ChatViewProps) {
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
const { environments } = useEnvironments();
const serverConfigs = useServerConfigs();
const primaryEnvironment = usePrimaryEnvironment();
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const environmentById = useMemo(
@@ -1280,7 +1286,6 @@ function ChatViewContent(props: ChatViewProps) {
},
};
}, [routeKind, routeThreadRef, routeThreadState]);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const settings = useEnvironmentSettings(environmentId);
// New-thread defaults live in the primary environment's settings.json (the
// settings UI never writes to remote environments), so read them from the
@@ -1669,23 +1674,29 @@ function ChatViewContent(props: ChatViewProps) {
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const serverThreadSupportsViewStatus =
serverThread != null &&
serverConfigs.get(serverThread.environmentId)?.environment.capabilities.threadViewStatus ===
true;
// Reading a finished thread clears the sidebar's Done badge. The visit is
// stamped at the turn's completion time — not now/updatedAt — so it clears
// exactly the completion the user is looking at: a wake or completion that
// lands later still gets its signal (markThreadVisited never moves the
// timestamp backwards).
// recorded by the server. A later completion retriggers this effect, so
// work that lands while the thread stays open is acknowledged too.
useEffect(() => {
const completedAt = serverThread?.latestTurn?.completedAt;
if (!serverThread?.id || !completedAt) return;
markThreadVisited(
scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
completedAt,
);
if (!serverThread?.id || !completedAt || !serverThreadSupportsViewStatus) return;
void markThreadViewed({
environmentId: serverThread.environmentId,
input: {
threadId: serverThread.id,
viewedAt: completedAt,
},
});
}, [
markThreadVisited,
markThreadViewed,
serverThread?.environmentId,
serverThread?.id,
serverThread?.latestTurn?.completedAt,
serverThreadSupportsViewStatus,
]);
useEffect(() => {
setMountedTerminalThreadKeys((currentThreadIds) => {
@@ -4101,6 +4112,7 @@ function ChatViewContent(props: ChatViewProps) {
// so the banner and the sidebar row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge);
const activeThreadPr = resolveThreadPr({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
@@ -4127,6 +4139,10 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadShell !== null && supportsSnooze
? threadWokeAt(activeThreadShell, { now: snoozeNow })
: null;
const activeThreadSupportsViewStatus =
activeThreadRef !== null &&
serverConfigs.get(activeThreadRef.environmentId)?.environment.capabilities.threadViewStatus ===
true;
useEffect(() => {
if (!activeThreadSnoozed) return;
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
@@ -4138,51 +4154,59 @@ function ChatViewContent(props: ChatViewProps) {
return () => window.clearTimeout(id);
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
const acknowledgeActiveThreadWoke = useCallback(() => {
if (activeThreadRef === null || activeThreadWokeAt === null) return;
markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);
}, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);
// Mirror of the sidebar's Woke pill for the open thread: same visit
// comparison, same merged/closed-PR suppression (finished work needs no
// wake-up call). Drives the dismissible composer banner below.
const activeThreadLastVisitedAt = useUiStateStore((store) =>
activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
);
if (activeThreadRef === null || activeThreadWokeAt === null || !activeThreadSupportsViewStatus)
return;
void markThreadViewed({
environmentId: activeThreadRef.environmentId,
input: {
threadId: activeThreadRef.threadId,
viewedAt: activeThreadWokeAt,
},
});
}, [activeThreadRef, activeThreadSupportsViewStatus, activeThreadWokeAt, markThreadViewed]);
// Mirror of the sidebar's Woke pill for the open thread. It uses the same
// server view comparison and change request settle rule.
const activeThreadLastViewedAt = activeThreadShell?.lastViewedAt;
const activeThreadWokeVisible = useMemo(() => {
if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false;
if (
!hasUnseenWake({
viewStatusSupported: activeThreadSupportsViewStatus,
wokeAt: activeThreadWokeAt,
lastViewedAt: activeThreadLastViewedAt,
})
)
return false;
if (activeThreadWokeAt === null) return false;
if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false;
const wokeAtMs = Date.parse(activeThreadWokeAt);
if (Number.isNaN(wokeAtMs)) return false;
// Having the thread open counts as a visit at completedAt (the effect
// above stamps it); folding that floor in here keeps a completion-
// triggered wake from flashing a banner for one frame before the stamp
// lands. An unparseable stored visit counts as never-visited: corrupt
// local data must not eat the wake signal.
const storedVisitMs = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
// triggered wake from flashing a banner for one frame before the stamp lands.
const completedAtMs = activeLatestTurn?.completedAt
? Date.parse(activeLatestTurn.completedAt)
: NaN;
const lastVisitedMs = Math.max(
Number.isNaN(storedVisitMs) ? -Infinity : storedVisitMs,
Number.isNaN(completedAtMs) ? -Infinity : completedAtMs,
);
return lastVisitedMs < wokeAtMs;
return Number.isNaN(completedAtMs) || completedAtMs < wokeAtMs;
}, [
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
activeThreadSupportsViewStatus,
activeThreadLastViewedAt,
activeThreadPr?.state,
activeThreadWokeAt,
autoSettleOnMerge,
]);
const activeThreadSettled = useMemo(() => {
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState: activeThreadPr?.state ?? null,
});
}, [
activeThreadPr?.state,
activeThreadShell,
autoSettleAfterDays,
autoSettleOnMerge,
nowMinute,
supportsSettlement,
]);
+56 -55
View File
@@ -77,6 +77,7 @@ import { useOpenPrLink } from "../lib/openPullRequestLink";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isMacPlatform } from "../lib/utils";
import {
readEnvironmentSupportsViewStatus,
readThreadShell,
useProject,
useProjects,
@@ -373,7 +374,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
} = props;
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: thread.environmentId,
@@ -449,12 +449,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
);
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = resolveThreadStatusPill({
thread: {
...thread,
lastVisitedAt,
},
});
const threadStatus = resolveThreadStatusPill({ thread });
const pr = resolveThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
@@ -1138,7 +1133,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar();
const markThreadUnread = useUiStateStore((state) => state.markThreadUnread);
const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, {
reportFailure: false,
});
const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded);
const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread);
const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo);
@@ -1207,16 +1204,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const projectExpanded = useUiStateStore((state) =>
resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys),
);
const threadLastVisitedAts = useUiStateStore(
useShallow((state) =>
projectThreads.map(
(thread) =>
state.threadLastVisitedAtById[
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
] ?? null,
),
),
);
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
@@ -1259,22 +1246,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}, [memberProjectByScopedKey, project.memberProjects, projectThreads]);
const { projectStatus, visibleProjectThreads, orderedProjectThreadKeys } = useMemo(() => {
const lastVisitedAtByThreadKey = new Map(
projectThreads.map((thread, index) => [
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
threadLastVisitedAts[index] ?? null,
]),
);
const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
const lastVisitedAt = lastVisitedAtByThreadKey.get(
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
);
return resolveThreadStatusPill({
thread: {
...thread,
...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
},
});
return resolveThreadStatusPill({ thread });
};
const visibleProjectThreads = sortThreads(
projectThreads.filter((thread) => thread.archivedAt === null),
@@ -1290,7 +1263,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
projectStatus,
visibleProjectThreads,
};
}, [projectThreads, threadLastVisitedAts, threadSortOrder]);
}, [projectThreads, threadSortOrder]);
const pinnedCollapsedThread = useMemo(() => {
const activeThreadKey = activeRouteThreadKey ?? undefined;
if (!activeThreadKey || projectExpanded) {
@@ -1311,22 +1284,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
showEmptyThreadState,
shouldShowThreadPanel,
} = useMemo(() => {
const lastVisitedAtByThreadKey = new Map(
projectThreads.map((thread, index) => [
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
threadLastVisitedAts[index] ?? null,
]),
);
const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
const lastVisitedAt = lastVisitedAtByThreadKey.get(
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
);
return resolveThreadStatusPill({
thread: {
...thread,
...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
},
});
return resolveThreadStatusPill({ thread });
};
const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
const previewThreads =
@@ -1362,7 +1321,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
projectExpanded,
projectThreads,
sidebarThreadPreviewCount,
threadLastVisitedAts,
visibleProjectThreads,
]);
@@ -1795,15 +1753,42 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const hasRunningThread = selectedThreadEntries.some(
({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null,
);
const canMarkUnread =
selectedThreadEntries.length > 0 &&
selectedThreadEntries.every(
({ thread }) =>
readEnvironmentSupportsViewStatus(thread.environmentId) &&
thread.latestTurn?.completedAt != null,
);
const clicked = await api.contextMenu.show(
buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }),
buildMultiSelectThreadContextMenuItems({ count, hasRunningThread, canMarkUnread }),
position,
);
if (clicked === "mark-unread") {
for (const { threadKey, thread } of selectedThreadEntries) {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
for (const { thread } of selectedThreadEntries) {
if (
!readEnvironmentSupportsViewStatus(thread.environmentId) ||
thread.latestTurn?.completedAt == null
)
continue;
const result = await markThreadUnread({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Success") continue;
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to mark threads unread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
clearSelection();
return;
@@ -2143,7 +2128,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
...(readEnvironmentSupportsViewStatus(thread.environmentId) &&
thread.latestTurn?.completedAt != null
? [{ id: "mark-unread", label: "Mark unread" }]
: []),
{ id: "copy-path", label: "Copy Path" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
@@ -2181,7 +2169,20 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
if (clicked === "mark-unread") {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
const result = await markThreadUnread({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to mark thread unread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
if (clicked === "copy-path") {
+55 -7
View File
@@ -11,6 +11,7 @@ import {
getVisibleThreadsForProject,
getProjectSortTimestamp,
hasUnseenCompletion,
hasUnseenWake,
isContextMenuPointerDown,
isSidebarNestedLinkClick,
isTrailingDoubleClick,
@@ -195,13 +196,21 @@ describe("buildBulkTitleRegenerationContextMenuItem", () => {
describe("buildMultiSelectThreadContextMenuItems", () => {
it("offers bulk archive with the selected count", () => {
expect(
buildMultiSelectThreadContextMenuItems({ count: 3, hasRunningThread: false }),
buildMultiSelectThreadContextMenuItems({
count: 3,
hasRunningThread: false,
canMarkUnread: true,
}),
).toContainEqual({ id: "archive", label: "Archive (3)", disabled: false });
});
it("disables bulk archive when a selected thread is running", () => {
expect(
buildMultiSelectThreadContextMenuItems({ count: 2, hasRunningThread: true }),
buildMultiSelectThreadContextMenuItems({
count: 2,
hasRunningThread: true,
canMarkUnread: true,
}),
).toContainEqual({ id: "archive", label: "Archive (2)", disabled: true });
});
});
@@ -269,13 +278,13 @@ describe("hasUnseenCompletion", () => {
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
lastViewedAt: "2026-03-09T10:04:00.000Z",
session: null,
}),
).toBe(true);
});
it("treats a missing client visit marker as read", () => {
it("treats missing server view state as read", () => {
expect(
hasUnseenCompletion({
hasActionableProposedPlan: false,
@@ -283,13 +292,52 @@ describe("hasUnseenCompletion", () => {
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: undefined,
lastViewedAt: undefined,
session: null,
}),
).toBe(false);
});
});
describe("hasUnseenWake", () => {
it("treats missing server view state as read", () => {
expect(
hasUnseenWake({
viewStatusSupported: true,
wokeAt: "2026-03-09T10:05:00.000Z",
lastViewedAt: null,
}),
).toBe(false);
});
it("suppresses wakes that an older server cannot acknowledge", () => {
expect(
hasUnseenWake({
viewStatusSupported: false,
wokeAt: "2026-03-09T10:05:00.000Z",
lastViewedAt: undefined,
}),
).toBe(false);
});
it("clears a wake only after its timestamp has been viewed", () => {
expect(
hasUnseenWake({
viewStatusSupported: true,
wokeAt: "2026-03-09T10:05:00.000Z",
lastViewedAt: "2026-03-09T10:04:00.000Z",
}),
).toBe(true);
expect(
hasUnseenWake({
viewStatusSupported: true,
wokeAt: "2026-03-09T10:05:00.000Z",
lastViewedAt: "2026-03-09T10:05:00.000Z",
}),
).toBe(false);
});
});
describe("createThreadJumpHintVisibilityController", () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -1053,7 +1101,7 @@ describe("resolveThreadStatusPill", () => {
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
lastViewedAt: undefined,
session: {
threadId: ThreadId.make("thread-1"),
status: "running" as const,
@@ -1137,7 +1185,7 @@ describe("resolveThreadStatusPill", () => {
...baseThread,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
lastViewedAt: "2026-03-09T10:04:00.000Z",
session: {
...baseThread.session,
status: "ready",
+22 -6
View File
@@ -87,9 +87,12 @@ export async function archiveSelectedThreadEntries<
export function buildMultiSelectThreadContextMenuItems(input: {
count: number;
hasRunningThread: boolean;
canMarkUnread: boolean;
}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
return [
{ id: "mark-unread", label: `Mark unread (${input.count})` },
...(input.canMarkUnread
? [{ id: "mark-unread" as const, label: `Mark unread (${input.count})` }]
: []),
{
id: "archive",
label: `Archive (${input.count})`,
@@ -154,7 +157,7 @@ type ThreadStatusInput = Pick<
| "session"
| "backgroundLiveness"
> & {
lastVisitedAt?: string | undefined;
lastViewedAt?: string | null | undefined;
};
export interface ThreadJumpHintVisibilityController {
@@ -253,11 +256,24 @@ export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return false;
if (!thread.lastViewedAt) return false;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
const lastViewedAt = Date.parse(thread.lastViewedAt);
if (Number.isNaN(lastViewedAt)) return true;
return completedAt > lastViewedAt;
}
export function hasUnseenWake(input: {
readonly viewStatusSupported: boolean;
readonly wokeAt: string | null;
readonly lastViewedAt: string | null | undefined;
}): boolean {
if (!input.viewStatusSupported || input.wokeAt === null) return false;
const wokeAt = Date.parse(input.wokeAt);
if (Number.isNaN(wokeAt)) return false;
if (input.lastViewedAt == null) return false;
const lastViewedAt = Date.parse(input.lastViewedAt);
return Number.isNaN(lastViewedAt) || lastViewedAt < wokeAt;
}
export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
+101 -33
View File
@@ -19,6 +19,7 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
import { CSS } from "@dnd-kit/utilities";
import {
canSnooze,
changeRequestAutoSettles,
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
@@ -115,7 +116,7 @@ import {
resolveActiveThreadRouteRef,
resolveThreadRouteTarget,
} from "../threadRoutes";
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
import { formatRelativeTimeLabel } from "../timestampFormat";
import type { SidebarThreadSummary } from "../types";
import { cn } from "~/lib/utils";
import { buildThreadActionMenuItems } from "./threadActionMenu.logic";
@@ -124,6 +125,7 @@ import {
formatWorkingDurationLabel,
firstValidTimestampMs,
hasUnseenCompletion,
hasUnseenWake,
isSidebarNestedLinkClick,
isTrailingDoubleClick,
orderItemsByPreferredIds,
@@ -657,8 +659,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
// False on environments whose server predates thread.settle/unsettle:
// the lifecycle affordances hide entirely rather than fail on click.
settlementSupported: boolean;
autoSettleOnMerge: boolean;
// Same contract for thread.snooze/unsnooze.
snoozeSupported: boolean;
// Read/unread and Woke acknowledgement require server-owned view state.
viewStatusSupported: boolean;
// Renders the pin glyph. Pinned cards keep the full settle/snooze quick
// actions: settling clears the pin server-side, and snoozing hides the
// card until wake with the pin intact underneath. The glyph is also the
@@ -732,7 +737,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
);
const threadKey = scopedThreadKey(threadRef);
const isRegeneratingTitle = thread.titleRegeneration != null;
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -757,25 +761,23 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
});
const prState = pr?.state ?? null;
// Same semantics as the legacy sidebar (never-visited counts as read):
// switching sidebars must not light up every historical thread as unread.
const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt });
// Missing server state counts as read so upgrading does not light up every
// historical thread as unread.
const isUnread = hasUnseenCompletion(thread);
const status = resolveSidebarThreadStatus(thread);
// A woken thread reappears at its original position (the sort is
// deliberately static), so the pill has to carry the weight. Snoozing is
// an explicit act, so the pill clears only when the user re-engages:
// reading a completion-triggered wake, clicking the pill, sending a
// message, settling, archiving — or finishing the work outright (merged
// or closed PR). Timer wakes survive a mere visit. An unparseable visit
// timestamp counts as never-visited — corrupt local data must not eat
// the wake signal.
const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt);
const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt);
// message, settling, archiving, or a change request state that settles the
// thread. Timer wakes survive a mere visit. An unparseable view timestamp
// counts as never viewed, so corrupt server data cannot hide the wake signal.
const isWoke =
wokeAtDate !== null &&
(lastVisitedDate === null || lastVisitedDate < wokeAtDate) &&
prState !== "merged" &&
prState !== "closed";
hasUnseenWake({
viewStatusSupported: props.viewStatusSupported,
wokeAt: props.wokeAt,
lastViewedAt: thread.lastViewedAt,
}) && !changeRequestAutoSettles(prState, props.autoSettleOnMerge);
// In-flight rows (working, or waiting on approval/input) fade as a whole:
// there is nothing for the user to do yet, so prominence is reserved for
// rows that need a human — done (unread), read-but-unsettled, failed, and
@@ -851,8 +853,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state up: the parent partitions rows with effectiveSettled,
// and a merged/closed PR auto-settles a thread — data only rows have.
// Report the PR state so the parent can apply the configured merge rule
// and the always-on close rule during partitioning.
useEffect(() => {
onChangeRequestState(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
@@ -1211,11 +1213,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
aria-label="Wake thread now"
onClick={handleUnsnoozeClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
isWoke && "group-hover/sidebar-row:static",
)}
>
<AlarmClockOffIcon className="size-3" />
<AlarmClockOffIcon className="mb-px size-3" />
</button>
)
) : !props.settlementSupported ? null : variantAction === "unsettle" ? (
@@ -1599,6 +1601,7 @@ export default function Sidebar() {
const { isMobile, setOpenMobile } = useSidebar();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
@@ -1678,18 +1681,31 @@ export default function Sidebar() {
[],
);
const { environments } = useEnvironments();
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const markThreadVisited = useUiStateStore((s) => s.markThreadVisited);
const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, {
reportFailure: false,
});
const markThreadViewed = useAtomCommand(threadEnvironment.markViewed, {
reportFailure: false,
});
const acknowledgeWoke = useCallback(
(threadRef: ScopedThreadRef, visitedAt: string) => {
markThreadVisited(scopedThreadKey(threadRef), visitedAt);
if (
serverConfigs.get(threadRef.environmentId)?.environment.capabilities.threadViewStatus !==
true
)
return;
void markThreadViewed({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, viewedAt: visitedAt },
});
},
[markThreadVisited],
[markThreadViewed, serverConfigs],
);
const routeTarget = useParams({
strict: false,
@@ -1801,8 +1817,8 @@ export default function Sidebar() {
// fresh clock whenever it recomputes.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
// closed PR auto-settles its thread on the next partition.
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -1900,7 +1916,6 @@ export default function Sidebar() {
// the partition works directly off live shells: no archived-snapshot
// merging, no optimistic holds. Archived threads remain hidden here —
// archive keeps its original "remove from sidebar" meaning.
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const {
pinnedThreads,
reorderablePinnedKeys,
@@ -1953,7 +1968,12 @@ export default function Sidebar() {
pinned.push(thread);
} else if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread);
} else {
@@ -1988,6 +2008,7 @@ export default function Sidebar() {
};
}, [
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestStateByKey,
nowMinute,
scopedProjectKeys,
@@ -2725,6 +2746,11 @@ export default function Sidebar() {
const regeneratableTitleThreads = titleRegenerationThreads.filter(
(thread) => thread.titleRegeneration == null,
);
const markUnreadThreads = selectedThreads.filter(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadViewStatus ===
true && thread.latestTurn?.completedAt != null,
);
const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({
supportedCount: titleRegenerationThreads.length,
actionableCount: regeneratableTitleThreads.length,
@@ -2747,7 +2773,9 @@ export default function Sidebar() {
]
: []),
...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []),
{ id: "mark-unread", label: `Mark unread (${count})` },
...(markUnreadThreads.length > 0
? [{ id: "mark-unread", label: `Mark unread (${markUnreadThreads.length})` }]
: []),
{ id: "delete", label: `Delete (${count})`, destructive: true },
],
position,
@@ -2852,9 +2880,25 @@ export default function Sidebar() {
return;
}
if (clicked.value === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
for (const thread of markUnreadThreads) {
const result = await markThreadUnread({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Success") continue;
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to mark threads unread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
// Keep the selection so a transient failure can be retried. Commands
// that already landed are idempotent.
return;
}
clearSelection();
return;
@@ -2947,6 +2991,9 @@ export default function Sidebar() {
const supportsTitleRegeneration =
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadTitleRegeneration === true;
const supportsViewStatus =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadViewStatus ===
true;
const isRegeneratingTitle = thread.titleRegeneration != null;
const isSettled = settledThreadKeysRef.current.has(threadKey);
const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
@@ -2961,12 +3008,14 @@ export default function Sidebar() {
isSettled,
isSnoozed,
canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
canMarkUnread: thread.latestTurn?.completedAt != null,
isRegeneratingTitle,
supports: {
settlement: supportsSettlement,
snooze: supportsSnooze,
pinning: supportsPinning,
titleRegeneration: supportsTitleRegeneration,
viewStatus: supportsViewStatus,
},
snoozePresets,
}),
@@ -3041,9 +3090,23 @@ export default function Sidebar() {
}
return;
}
case "mark-unread":
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
case "mark-unread": {
const result = await markThreadUnread({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to mark thread unread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
case "copy-path":
if (!threadWorkspacePath) {
toastManager.add(
@@ -3532,6 +3595,7 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSettlement === true
}
autoSettleOnMerge={autoSettleOnMerge}
snoozeSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSnooze === true
@@ -3540,6 +3604,10 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadPinning === true
}
viewStatusSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadViewStatus === true
}
isPinned={section === "pinned"}
sortable={sortable}
snoozeWakeLabelText={
@@ -144,10 +144,10 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.4" />
<stop style={{ stopColor: "var(--stage-night-glow-highlight)" }} stopOpacity="0.4" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-night-secondary)" }}
style={{ stopColor: "var(--stage-night-glow-secondary)" }}
stopOpacity="0.16"
/>
<stop offset="1" style={{ stopColor: "var(--stage-night-bottom)" }} stopOpacity="0" />
@@ -177,7 +177,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
))}
</g>
<g
style={{ stroke: "var(--stage-night-line)" }}
style={{ stroke: "var(--stage-night-sparkle)" }}
strokeLinecap="round"
strokeOpacity="0.7"
strokeWidth="0.6"
@@ -274,10 +274,10 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.34" />
<stop style={{ stopColor: "var(--stage-art-celeste-highlight)" }} stopOpacity="0.34" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-art-secondary)" }}
style={{ stopColor: "var(--stage-art-celeste-secondary)" }}
stopOpacity="0.18"
/>
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
@@ -290,7 +290,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
gradientUnits="userSpaceOnUse"
>
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.3" />
<stop style={{ stopColor: "var(--stage-art-violet-highlight)" }} stopOpacity="0.3" />
<stop
offset="0.52"
style={{ stopColor: "var(--stage-art-tertiary)" }}
@@ -301,7 +301,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
<path
d="M8 0H0V8"
style={{ stroke: "var(--stage-art-line)" }}
style={{ stroke: "var(--stage-art-grid-line)" }}
strokeOpacity="0.14"
strokeWidth="0.5"
/>
@@ -309,7 +309,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
<path
d="M32 0H0V32"
style={{ stroke: "var(--stage-art-line)" }}
style={{ stroke: "var(--stage-art-grid-line)" }}
strokeOpacity="0.26"
strokeWidth="0.6"
/>
@@ -1,8 +1,4 @@
import {
scopeProjectRef,
scopedThreadKey,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import type { VcsStatusResult } from "@t3tools/contracts";
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
@@ -11,7 +7,6 @@ import { useProject } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { vcsEnvironment } from "../state/vcs";
import { useUiStateStore } from "../uiStateStore";
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
import type { SidebarThreadSummary } from "../types";
@@ -230,10 +225,6 @@ export function ThreadStatusLabel({
* thread status dot, matching the sidebar's leading indicators.
*/
export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const lastVisitedAt = useUiStateStore(
(state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
);
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
@@ -255,12 +246,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
gitStatus: gitStatus.data,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const threadStatus = resolveThreadStatusPill({
thread: {
...thread,
lastVisitedAt,
},
});
const threadStatus = resolveThreadStatusPill({ thread });
if (!prStatus && !threadStatus) {
return null;
@@ -115,8 +115,11 @@ export function DraftHeroHeadline({
return;
}
const project = entry.targetProject;
// Changing the repo of a draft moves the typed content along:
// the user started writing in the wrong project, not a new task.
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
carryComposerContent: true,
});
}}
>
@@ -610,7 +610,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
/>
<TimelineMinimap
items={minimapItems}
bottomInset={contentInsetEndAdjustment}
hasPersistentGutter={minimapHasPersistentGutter}
hitStripWidth={minimapHitStripWidth}
stripMap={minimapStripMap}
@@ -712,14 +711,12 @@ function timelineMinimapEventTargetsPreview(target: EventTarget): boolean {
}
function TimelineMinimap({
bottomInset,
hasPersistentGutter,
hitStripWidth,
items,
stripMap,
onSelect,
}: {
bottomInset: number;
hasPersistentGutter: boolean;
hitStripWidth: number;
items: ReadonlyArray<TimelineMinimapItem>;
@@ -779,19 +776,16 @@ function TimelineMinimap({
return null;
}
const safeBottomInset = Math.max(0, Math.ceil(bottomInset));
return (
<div
className={cn(
"group/minimap pointer-events-none absolute top-0 left-0 z-40 hidden w-18 [@media(pointer:fine)]:block",
"group/minimap pointer-events-none absolute inset-y-0 left-0 z-40 hidden w-18 [@media(pointer:fine)]:block",
hasPersistentGutter
? "opacity-100"
: "opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
)}
data-testid="timeline-minimap"
data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
style={{ bottom: safeBottomInset }}
>
<div className="relative h-full w-full select-none">
<button
@@ -19,7 +19,7 @@ export function ClerkUserProfilePage({
}) {
return (
<div className={cn("w-full min-w-0 text-foreground", className)}>
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:pr-8">
<div className="min-w-0">
<h2 className="text-[1.0625rem] leading-6 font-semibold">{title}</h2>
{description ? (
@@ -44,7 +44,7 @@ describe("StyledDiffCodeView", () => {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
paddingTop: 0,
paddingBottom: 0,
paddingBottom: 8,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
});
@@ -304,11 +304,16 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
// Pierre uses its general file spacing as a fallback in expanded-file layout paths.
// Keep it zero alongside the explicit paddings or expanding the first file can
// Keep it zero alongside the explicit paddingTop or expanding the first file can
// reintroduce the library's default 8px gap above its header.
spacing: 0,
paddingTop: 0,
paddingBottom: 0,
// Unlike the gap above, the 8px under a file's last line is painted
// unconditionally by Pierre's stylesheet (`--diffs-gap-fallback`), so the metric has
// to count it: at zero every expanded file's virtual height ran 8px short of its
// rendered height, and the end of the list sat past the reachable scroll range —
// one clipped file row per expanded file above it.
paddingBottom: 8,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
}}
@@ -169,6 +169,7 @@ export function PreviewMoreMenu({
type="button"
onClick={callTab(bridge.resetZoom)}
aria-label="Reset zoom"
className="[:hover,[data-pressed]]:bg-foreground/10"
disabled={tabDisabled}
>
<RotateCcw />
@@ -1,6 +1,8 @@
import { jsx } from "react/jsx-runtime";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { getPreviewPanelMaxWidth } from "./PreviewPanelShell";
import { getPreviewPanelMaxWidth, PreviewPanelShell } from "./PreviewPanelShell";
describe("getPreviewPanelMaxWidth", () => {
it("allows the panel to use 70% of an ultra-wide viewport without a pixel ceiling", () => {
@@ -10,4 +12,12 @@ describe("getPreviewPanelMaxWidth", () => {
it("rounds fractional CSS pixels down", () => {
expect(getPreviewPanelMaxWidth(2_001)).toBe(1_400);
});
it("keeps inline panels inside their containing workspace", () => {
const markup = renderToStaticMarkup(
jsx(PreviewPanelShell, { mode: "inline", defaultWidth: 1_000, children: "Panel" }),
);
expect(markup).toContain("max-w-full");
});
});
@@ -51,7 +51,7 @@ export function PreviewPanelShell(props: {
return (
<div
className={cn(
"relative flex h-full min-h-0 min-w-0 flex-col self-stretch bg-background",
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
isInline
? props.maximized
? "flex-1 border-l border-border"
@@ -3,7 +3,7 @@ import { CircleIcon } from "lucide-react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
import { PullRequestFiltersMenu } from "./PullRequestListFilters";
import { PullRequestFiltersMenu, pullRequestProjectKey } from "./PullRequestListFilters";
function findValueChange(
node: ReactNode,
@@ -129,7 +129,7 @@ describe("pull request filters menu", () => {
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(`${environmentId} ${projectId}`);
radioGroup?.props.onValueChange(pullRequestProjectKey({ id: projectId, environmentId }));
expect(onProject).not.toHaveBeenCalled();
radioGroup?.props.onValueChange("all");
@@ -159,7 +159,23 @@ describe("pull request filters menu", () => {
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(`env-2 ${projectId}`);
radioGroup?.props.onValueChange(
pullRequestProjectKey({ id: projectId, environmentId: "env-2" as EnvironmentId }),
);
expect(onProject).toHaveBeenCalledWith(projectId, "env-2");
});
it("does not collide when environment and project ids contain spaces", () => {
expect(
pullRequestProjectKey({
environmentId: "a b" as EnvironmentId,
id: "c" as ProjectId,
}),
).not.toBe(
pullRequestProjectKey({
environmentId: "a" as EnvironmentId,
id: "b c" as ProjectId,
}),
);
});
});
@@ -122,10 +122,10 @@ const UNFILTERED_VALUE = "all";
* A project's own radio value, carrying the server along with the id: the id alone is only
* unique within its own server, so two rows sharing one would otherwise both read as checked.
*/
const projectMenuValue = (project: {
export const pullRequestProjectKey = (project: {
readonly id: ProjectId;
readonly environmentId: EnvironmentId;
}) => `${project.environmentId} ${project.id}`;
}) => JSON.stringify([project.environmentId, project.id]);
const DRAFT_OPTIONS = [
{ value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
@@ -247,7 +247,7 @@ export function PullRequestFiltersMenu({
* the reader is already choosing between projects, rather than as a count above the list
* that says something is missing without saying which.
*/
unavailable: ReadonlyMap<ProjectId, string>;
unavailable: ReadonlyMap<string, string>;
/** The environment comes with the project id, since picking a row picks a specific server's copy of it. */
onProject: (projectId: ProjectId | undefined, environmentId: EnvironmentId | undefined) => void;
}) {
@@ -350,7 +350,7 @@ export function PullRequestFiltersMenu({
value={
projectId === undefined || projectEnvironmentId === undefined
? ALL_PROJECTS_VALUE
: projectMenuValue({ id: projectId, environmentId: projectEnvironmentId })
: pullRequestProjectKey({ id: projectId, environmentId: projectEnvironmentId })
}
onValueChange={(next) => {
if (next === ALL_PROJECTS_VALUE) {
@@ -359,7 +359,7 @@ export function PullRequestFiltersMenu({
}
// The value carries both halves, since the id alone cannot tell two servers' rows
// apart once they share one.
const project = projects.find((candidate) => projectMenuValue(candidate) === next);
const project = projects.find((candidate) => pullRequestProjectKey(candidate) === next);
if (
project !== undefined &&
(project.id !== projectId || project.environmentId !== projectEnvironmentId)
@@ -379,14 +379,16 @@ export function PullRequestFiltersMenu({
as a broken menu rather than as a workspace with three unreadable repositories. */}
{projects
.toSorted(
(left, right) => Number(unavailable.has(left.id)) - Number(unavailable.has(right.id)),
(left, right) =>
Number(unavailable.has(pullRequestProjectKey(left))) -
Number(unavailable.has(pullRequestProjectKey(right))),
)
.map((project) => {
const reason = unavailable.get(project.id);
const reason = unavailable.get(pullRequestProjectKey(project));
return (
<MenuRadioItem
key={projectMenuValue(project)}
value={projectMenuValue(project)}
key={pullRequestProjectKey(project)}
value={pullRequestProjectKey(project)}
disabled={reason !== undefined}
title={reason}
>
@@ -1,4 +1,4 @@
import type { EnvironmentId, PullRequestListEntry } from "@t3tools/contracts";
import type { EnvironmentId, ProjectId, PullRequestListEntry } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -710,6 +710,20 @@ describe("merging the environments' own listings", () => {
);
});
it("keeps project errors scoped to the environment that reported them", () => {
const error = {
projectId: "project-1" as ProjectId,
projectTitle: "Web",
message: "Not signed in",
} as const;
const merged = mergePullRequestLists([
[ENV_1, answer({ errors: [error] })],
[ENV_2, answer()],
]);
expect(merged?.errors).toEqual([{ ...error, environmentId: ENV_1 }]);
});
it("folds a host reached from two environments into one switcher row", () => {
const merged = mergePullRequestLists([
[ENV_1, answer()],
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
import {
EnvironmentId,
PullRequestListEntry,
PullRequestListProjectError,
PullRequestListResult,
resolvePullRequestAuthorFilter,
} from "@t3tools/contracts";
@@ -27,6 +28,10 @@ export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
readonly environmentId: EnvironmentId;
}
export interface EnvironmentPullRequestError extends PullRequestListProjectError {
readonly environmentId: EnvironmentId;
}
export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
@@ -452,7 +457,7 @@ export interface MergedPullRequestList {
readonly viewers: PullRequestViewers;
readonly providers: PullRequestListResult["providers"];
readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
readonly errors: PullRequestListResult["errors"];
readonly errors: ReadonlyArray<EnvironmentPullRequestError>;
readonly truncated: boolean;
readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
/**
@@ -476,7 +481,7 @@ export function mergePullRequestLists(
const truncatedEnvironments: string[] = [];
const providers = new Map<string, PullRequestListResult["providers"][number]>();
const entries: EnvironmentPullRequestEntry[] = [];
const errors: Array<PullRequestListResult["errors"][number]> = [];
const errors: EnvironmentPullRequestError[] = [];
const nextCursors: Record<string, PullRequestListCursors> = {};
let truncated = false;
for (const [environmentId, answer] of answers) {
@@ -498,7 +503,7 @@ export function mergePullRequestLists(
);
}
entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
errors.push(...answer.errors);
errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
truncated ||= answer.truncated;
if (answer.truncated) truncatedEnvironments.push(environmentId);
if (Object.keys(answer.nextCursors).length > 0) {
@@ -559,12 +564,18 @@ const EnvironmentPullRequestEntrySchema = Schema.Struct({
environmentId: EnvironmentId,
});
const EnvironmentPullRequestErrorSchema = Schema.Struct({
...PullRequestListProjectError.fields,
environmentId: EnvironmentId,
});
const decodeSnapshot = Schema.decodeUnknownOption(
Schema.Struct({
scope: Schema.String,
data: Schema.Struct({
...PullRequestListResult.fields,
entries: Schema.Array(EnvironmentPullRequestEntrySchema),
errors: Schema.Array(EnvironmentPullRequestErrorSchema),
// Per environment here, unlike the wire shape, which is per repository within one.
nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
truncatedEnvironments: Schema.Array(Schema.String),
@@ -493,6 +493,9 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays
? ["Auto-settle inactive threads"]
: []),
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge
? ["Auto-settle merged threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...getChangedTypographySettingLabels(settings),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
@@ -547,6 +550,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge,
settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -628,6 +632,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
@@ -1828,9 +1833,36 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("auto-settle-merged-threads")}
description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."
resetAction={
settings.sidebarAutoSettleOnMerge !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? (
<SettingResetButton
label="auto-settle on merge"
onClick={() =>
updateSettings({
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
})
}
/>
) : null
}
control={
<Switch
checked={settings.sidebarAutoSettleOnMerge}
onCheckedChange={(checked) =>
updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })
}
aria-label="Auto-settle merged threads"
/>
}
/>
<SettingsRow
{...searchableSetting("auto-settle-inactive-threads")}
description="Sidebar threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
description="Sidebar threads with no activity for this long settle automatically."
resetAction={
settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? (
@@ -19,7 +19,7 @@ import {
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
import { usePrimaryEnvironment } from "../../state/environments";
import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
import { useEnvironmentQuery } from "../../state/query";
import { sourceControlEnvironment } from "../../state/sourceControl";
import { Badge } from "../ui/badge";
@@ -508,7 +508,15 @@ function EmptySourceControlDiscovery({
}
export function SourceControlSettingsPanel() {
const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const fallbackEnvironment =
environments.find((environment) => environment.connection.phase === "connected") ??
environments[0] ??
null;
const environmentId =
primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
const discovery = useEnvironmentQuery(
environmentId === null
? null
@@ -561,7 +569,9 @@ export function SourceControlSettingsPanel() {
>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
{item.kind === "git" && isPrimaryEnvironment ? (
<GitFetchIntervalSettings />
) : undefined}
</DiscoveryItemRow>
))}
</SettingsSection>
@@ -587,7 +597,7 @@ export function SourceControlSettingsPanel() {
/>
)}
{environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
{isPrimaryEnvironment ? <SourceControlWritingSettingsSection /> : null}
</SettingsPageContainer>
);
}
@@ -103,6 +103,11 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Auto-settle inactive threads",
to: "/settings/general",
},
{
id: "auto-settle-merged-threads",
title: "Auto-settle merged threads",
to: "/settings/general",
},
{
id: "time-format",
title: "Time format",
@@ -91,7 +91,7 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
<T3Wordmark />
<span
className={cn(
"truncate text-sm font-medium tracking-tight",
"-translate-y-px truncate text-sm font-medium tracking-tight",
onBackdrop ? "text-white/70" : "text-muted-foreground",
)}
>
@@ -8,8 +8,15 @@ const baseState: ThreadActionMenuState = {
isSettled: false,
isSnoozed: false,
canSnoozeNow: true,
canMarkUnread: true,
isRegeneratingTitle: false,
supports: { settlement: true, snooze: true, pinning: true, titleRegeneration: true },
supports: {
settlement: true,
snooze: true,
pinning: true,
titleRegeneration: true,
viewStatus: true,
},
snoozePresets: [
{ id: "hour", label: "In 1 hour", whenLabel: "3:00 PM", snoozedUntil: "2026-08-07T15:00:00Z" },
],
@@ -24,9 +31,15 @@ describe("buildThreadActionMenuItems", () => {
expect(
ids({
...baseState,
supports: { settlement: false, snooze: false, pinning: false, titleRegeneration: false },
supports: {
settlement: false,
snooze: false,
pinning: false,
titleRegeneration: false,
viewStatus: false,
},
}),
).toEqual(["rename", "mark-unread", "copy-path", "copy-thread-id", "delete"]);
).toEqual(["rename", "copy-path", "copy-thread-id", "delete"]);
});
it("includes branch items only for threads with a branch", () => {
@@ -59,6 +72,10 @@ describe("buildThreadActionMenuItems", () => {
expect(item).toMatchObject({ label: "Regenerating…", disabled: true });
});
it("hides mark unread until the thread has a completed turn", () => {
expect(ids({ ...baseState, canMarkUnread: false })).not.toContain("mark-unread");
});
it("marks delete as destructive and keeps it last", () => {
const items = buildThreadActionMenuItems({ ...baseState, branch: "main" });
expect(items.at(-1)).toMatchObject({ id: "delete", destructive: true });
@@ -29,12 +29,14 @@ export interface ThreadActionMenuState {
readonly isSettled: boolean;
readonly isSnoozed: boolean;
readonly canSnoozeNow: boolean;
readonly canMarkUnread: boolean;
readonly isRegeneratingTitle: boolean;
readonly supports: {
readonly settlement: boolean;
readonly snooze: boolean;
readonly pinning: boolean;
readonly titleRegeneration: boolean;
readonly viewStatus: boolean;
};
readonly snoozePresets: ReadonlyArray<SnoozePreset>;
}
@@ -98,7 +100,9 @@ export function buildThreadActionMenuItems(
},
]
: []),
{ id: "mark-unread", label: "Mark unread" },
...(state.supports.viewStatus && state.canMarkUnread
? [{ id: "mark-unread" as const, label: "Mark unread" }]
: []),
{ id: "copy-path", label: "Copy path", icon: "copy" },
...(state.branch ? [{ id: "copy-branch" as const, label: "Copy branch", icon: "copy" }] : []),
{ id: "copy-thread-id", label: "Copy thread ID", icon: "copy" },
+56
View File
@@ -289,6 +289,62 @@ describe("composerDraftStore clearComposerContent", () => {
});
});
describe("composerDraftStore moveComposerPromptAndImages", () => {
const sourceDraftId = DraftId.make("draft-move-source");
const destinationDraftId = DraftId.make("draft-move-destination");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
resetComposerDraftStore();
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("moves prompt and images to the destination without revoking preview URLs", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(sourceDraftId, "fix the login redirect");
store.addImages(sourceDraftId, [makeImage({ id: "img-move", previewUrl: "blob:move" })]);
store.moveComposerPromptAndImages(sourceDraftId, destinationDraftId);
expect(draftByKey(sourceDraftId)).toBeUndefined();
const destination = draftByKey(destinationDraftId);
expect(destination?.prompt).toBe("fix the login redirect");
expect(destination?.images.map((image) => image.id)).toEqual(["img-move"]);
expect(revokeSpy).not.toHaveBeenCalled();
});
it("keeps session-bound contexts on the source and strips their placeholders from the moved prompt", () => {
const sourceThreadId = ThreadId.make("thread-move-source");
const sourceThreadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, sourceThreadId);
const store = useComposerDraftStore.getState();
store.addTerminalContext(sourceThreadRef, makeTerminalContext({ id: "ctx-stay" }));
store.setPrompt(sourceThreadRef, `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} explain this error`);
store.moveComposerPromptAndImages(sourceThreadRef, destinationDraftId);
const source = draftFor(sourceThreadId, TEST_ENVIRONMENT_ID);
expect(source?.terminalContexts.map((context) => context.id)).toEqual(["ctx-stay"]);
expect(source?.prompt).toBe(INLINE_TERMINAL_CONTEXT_PLACEHOLDER);
expect(draftByKey(destinationDraftId)?.prompt).toBe(" explain this error");
});
it("is a no-op when source and destination are the same target", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(sourceDraftId, "keep me");
store.moveComposerPromptAndImages(sourceDraftId, sourceDraftId);
expect(draftByKey(sourceDraftId)?.prompt).toBe("keep me");
});
});
describe("composerDraftStore syncPersistedAttachments", () => {
const threadId = ThreadId.make("thread-sync-persisted");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
+66
View File
@@ -38,6 +38,7 @@ import {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
normalizeTerminalContextText,
stripInlineTerminalContextPlaceholders,
} from "./lib/terminalContext";
import {
type ElementContextDraft,
@@ -527,6 +528,15 @@ interface ComposerDraftStoreState {
* session-bound contexts would destroy state nothing can restore.
*/
clearComposerPromptAndImages: (threadRef: ComposerThreadTarget) => void;
/**
* Moves the prompt text and image attachments from one composer target to
* another. Used when a draft changes project: the new project gets its own
* draft session and the typed content follows it. Session-bound extras
* (terminal / element contexts, preview annotations, review comments) stay
* on the source — they reference sessions of the source thread that the
* destination cannot use.
*/
moveComposerPromptAndImages: (from: ComposerThreadTarget, to: ComposerThreadTarget) => void;
}
export interface EffectiveComposerModelState {
@@ -3474,6 +3484,62 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
moveComposerPromptAndImages: (from, to) => {
const fromKey = resolveComposerDraftKey(get(), from) ?? "";
const toKey = resolveComposerDraftKey(get(), to) ?? "";
if (fromKey.length === 0 || toKey.length === 0 || fromKey === toKey) {
return;
}
set((state) => {
const source = state.draftsByThreadKey[fromKey];
if (!source) {
return state;
}
const destination = state.draftsByThreadKey[toKey] ?? createEmptyThreadDraft();
// Inline placeholders reference the source's terminal contexts,
// which stay behind; re-anchor the moved prompt to whatever
// contexts the destination already holds.
const movedPrompt = ensureInlineTerminalContextPlaceholders(
stripInlineTerminalContextPlaceholders(source.prompt),
destination.terminalContexts.length,
);
const nextDestination: ComposerThreadDraftState = {
...destination,
prompt: movedPrompt,
images: [...destination.images, ...source.images],
nonPersistedImageIds: [
...destination.nonPersistedImageIds,
...source.nonPersistedImageIds,
],
persistedAttachments: [
...destination.persistedAttachments,
...source.persistedAttachments,
],
};
// Same clearing shape as clearComposerPromptAndImages, but the
// preview URLs are NOT revoked: the images moved and their blobs
// are still referenced from the destination.
const nextSource: ComposerThreadDraftState = {
...source,
prompt: ensureInlineTerminalContextPlaceholders("", source.terminalContexts.length),
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
};
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextSource)) {
delete nextDraftsByThreadKey[fromKey];
} else {
nextDraftsByThreadKey[fromKey] = nextSource;
}
if (shouldRemoveDraft(nextDestination)) {
delete nextDraftsByThreadKey[toKey];
} else {
nextDraftsByThreadKey[toKey] = nextDestination;
}
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
};
},
{
+33
View File
@@ -74,6 +74,14 @@ export function useNewThreadHandler() {
envMode?: DraftThreadEnvMode;
startFromOrigin?: boolean;
replace?: boolean;
/**
* Move the viewed draft's typed content (prompt + images) into the
* draft this request lands on. Set by the draft repo picker: the
* user started writing in the wrong project and the text should
* follow them. Explicit new-thread surfaces leave this unset and
* keep mint-fresh semantics.
*/
carryComposerContent?: boolean;
},
// Which draft the thread ended up in, so a caller that has something to put in it — a
// prepared checkout, a task to write — addresses that one rather than looking the project
@@ -85,6 +93,7 @@ export function useNewThreadHandler() {
getDraftSession,
getDraftThread,
applyStickyState,
moveComposerPromptAndImages,
setDraftThreadContext,
setLogicalProjectDraftThreadId,
setModelSelection,
@@ -126,6 +135,27 @@ export function useNewThreadHandler() {
carrySourceShell?.interactionMode ??
carrySourceDraft?.interactionMode ??
null;
// Content only moves when the caller opted in and the user is looking
// at a draft. The content check happens at move time, not here: the
// paths below await, and text typed during those awaits must still
// come along.
const carryContentSourceDraftId =
options?.carryComposerContent === true && currentRouteTarget?.kind === "draft"
? currentRouteTarget.draftId
: null;
const carryComposerContentTo = (destinationDraftId: DraftId) => {
if (
carryContentSourceDraftId &&
carryContentSourceDraftId !== destinationDraftId &&
// Never clobber a destination the user already invested in — the
// move overwrites the destination prompt, so a concurrent repo
// change that carried content first must win.
!composerDraftHasUserContent(getComposerDraft(destinationDraftId)) &&
composerDraftHasUserContent(getComposerDraft(carryContentSourceDraftId))
) {
moveComposerPromptAndImages(carryContentSourceDraftId, destinationDraftId);
}
};
const project = projects.find(
(candidate) =>
candidate.id === projectRef.projectId &&
@@ -267,6 +297,7 @@ export function useNewThreadHandler() {
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
},
);
carryComposerContentTo(emptyStoredDraftThread.draftId);
const opened = {
draftId: emptyStoredDraftThread.draftId,
threadId: emptyStoredDraftThread.threadId,
@@ -354,6 +385,7 @@ export function useNewThreadHandler() {
interactionMode: racedDraft.interactionMode,
...pickExplicitWorkspaceOptions(options),
});
carryComposerContentTo(racedDraft.draftId);
await router.navigate({
to: "/draft/$draftId",
params: { draftId: racedDraft.draftId },
@@ -385,6 +417,7 @@ export function useNewThreadHandler() {
// whatever sticky state just wrote".
setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
}
carryComposerContentTo(draftId);
await router.navigate({
to: "/draft/$draftId",
+16 -4
View File
@@ -1,4 +1,4 @@
import { scopeProjectRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
@@ -27,10 +27,10 @@ import {
readEnvironmentSupportsSettlement,
readEnvironmentSupportsSnooze,
readEnvironmentSupportsTitleRegeneration,
readEnvironmentSupportsViewStatus,
readThreadShell,
} from "../state/entities";
import { readLocalApi } from "../localApi";
import { useUiStateStore } from "../uiStateStore";
import { useCopyToClipboard } from "./useCopyToClipboard";
import { useNewThreadHandler } from "./useHandleNewThread";
import { useClientSettings } from "./useSettings";
@@ -78,8 +78,11 @@ export function useThreadActionMenu(input: {
reportFailure: false,
});
const handleNewThread = useNewThreadHandler();
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, {
reportFailure: false,
});
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
@@ -118,6 +121,7 @@ export function useThreadActionMenu(input: {
snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
viewStatus: readEnvironmentSupportsViewStatus(threadRef.environmentId),
};
const isRegeneratingTitle = thread.titleRegeneration != null;
const snoozePresets = resolveSnoozePresets(now, timestampFormat);
@@ -132,10 +136,12 @@ export function useThreadActionMenu(input: {
// parked-thread banner within the same minute.
now: `${now.toISOString().slice(0, 16)}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
}),
isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
canMarkUnread: thread.latestTurn?.completedAt != null,
isRegeneratingTitle,
supports,
snoozePresets,
@@ -226,7 +232,12 @@ export function useThreadActionMenu(input: {
);
return;
case "mark-unread":
markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
await reportFailure("Failed to mark thread unread", () =>
markThreadUnread({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
}),
);
return;
case "copy-path": {
const workspacePath = thread.worktreePath ?? projectCwd;
@@ -284,6 +295,7 @@ export function useThreadActionMenu(input: {
},
[
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
confirmThreadDelete,
copyBranchToClipboard,
+27 -9
View File
@@ -2,7 +2,6 @@ import {
parseScopedThreadKey,
scopeProjectRef,
scopeThreadRef,
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSettle, canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
@@ -26,13 +25,13 @@ import {
readEnvironmentSupportsPinReorder,
readEnvironmentSupportsSettlement,
readEnvironmentSupportsSnooze,
readEnvironmentSupportsViewStatus,
readEnvironmentThreadRefs,
readProject,
readThreadShell,
readThreadShells,
} from "../state/entities";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { useUiStateStore } from "../uiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
@@ -167,6 +166,9 @@ export function useThreadActions() {
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const markThreadViewed = useAtomCommand(threadEnvironment.markViewed, {
reportFailure: false,
});
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
@@ -181,7 +183,6 @@ export function useThreadActions() {
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
const router = useRouter();
const handleNewThread = useNewThreadHandler();
// Keep a ref so archiveThread can call handleNewThread without appearing in
@@ -234,8 +235,15 @@ export function useThreadActions() {
return archiveResult;
}
const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
if (wokeAt !== null) {
markThreadVisited(scopedThreadKey(threadRef), wokeAt);
if (wokeAt !== null && readEnvironmentSupportsViewStatus(threadRef.environmentId)) {
void markThreadViewed({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
viewedAt: wokeAt,
expectedLastViewedAt: thread.lastViewedAt ?? null,
},
});
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
opts.onArchived?.();
@@ -252,7 +260,7 @@ export function useThreadActions() {
return archiveResult;
},
[archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],
[archiveThreadMutation, getCurrentRouteThreadRef, markThreadViewed, resolveThreadTarget],
);
const unarchiveThread = useCallback(
@@ -505,12 +513,22 @@ export function useThreadActions() {
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
if (result._tag === "Success" && wokeAt !== null) {
markThreadVisited(scopedThreadKey(target), wokeAt);
if (
result._tag === "Success" &&
wokeAt !== null &&
readEnvironmentSupportsViewStatus(target.environmentId)
) {
void markThreadViewed({
environmentId: target.environmentId,
input: {
threadId: target.threadId,
viewedAt: wokeAt,
},
});
}
return result;
},
[markThreadVisited, resolveThreadTarget, settleThreadMutation],
[markThreadViewed, resolveThreadTarget, settleThreadMutation],
);
const unsettleThread = useCallback(
+57 -29
View File
@@ -266,8 +266,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
@layer base {
:root {
/* Dev artwork defaults. Built-in themes override these seven pigments in
the components layer; Nightly derives a darker matching palette. */
/* Keep the original T3 Code artwork palettes as the defaults. Built-in
themes override them with their own pigments in the components layer. */
--stage-art-top: oklch(0.782169 0.123386 240.226);
--stage-art-mid: oklch(0.616111 0.195824 259.735);
--stage-art-bottom: oklch(0.441553 0.232394 265.474);
@@ -275,33 +275,23 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--stage-art-secondary: oklch(0.794668 0.12136 235.46);
--stage-art-tertiary: oklch(0.678991 0.170261 275.365);
--stage-art-line: oklch(0.959666 0.029238 218.179);
--stage-night-top: color-mix(
in oklch,
var(--stage-art-top) 38%,
oklch(0.283792 0.117327 297.201)
);
--stage-night-mid: color-mix(
in oklch,
var(--stage-art-mid) 38%,
oklch(0.227147 0.086086 277.99)
);
--stage-night-bottom: color-mix(
in oklch,
var(--stage-art-bottom) 38%,
oklch(0.200528 0.055699 261.216)
);
--stage-night-highlight: var(--stage-art-highlight);
--stage-night-secondary: color-mix(
in oklch,
var(--stage-art-secondary) 55%,
var(--stage-night-mid)
);
--stage-night-tertiary: color-mix(
in oklch,
var(--stage-art-tertiary) 60%,
var(--stage-night-top)
);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, oklch(1 0 0));
--stage-art-celeste-highlight: oklch(0.968763 0.045822 196.42);
--stage-art-celeste-secondary: oklch(0.827395 0.126071 211.26);
--stage-art-violet-highlight: oklch(0.895381 0.053248 286.447);
--stage-art-grid-line: oklch(0.966822 0.01757 239.99);
--stage-night-base-top: oklch(0.283792 0.117327 297.201);
--stage-night-base-mid: oklch(0.227147 0.086086 277.99);
--stage-night-base-bottom: oklch(0.200528 0.055699 261.216);
--stage-night-top: var(--stage-night-base-top);
--stage-night-mid: var(--stage-night-base-mid);
--stage-night-bottom: var(--stage-night-base-bottom);
--stage-night-highlight: oklch(0.707246 0.157418 252.091);
--stage-night-secondary: oklch(0.600473 0.182225 277.296);
--stage-night-tertiary: oklch(0.62583 0.210886 305.994);
--stage-night-line: oklch(0.938794 0.029114 273.103);
--stage-night-glow-highlight: oklch(0.553749 0.176543 271.958);
--stage-night-glow-secondary: oklch(0.345571 0.117466 273.568);
--stage-night-sparkle: oklch(0.880867 0.057747 269.011);
}
.dark {
@@ -510,6 +500,44 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--stage-art-line: oklch(0.940582 0.032921 299.076);
}
:is(html[data-theme-id="t3-chat"], html[data-theme-id="ocean"], html[data-theme-id="iris"]) {
--stage-night-top: color-mix(in oklch, var(--stage-art-top) 38%, var(--stage-night-base-top));
--stage-night-mid: color-mix(in oklch, var(--stage-art-mid) 38%, var(--stage-night-base-mid));
--stage-night-bottom: color-mix(
in oklch,
var(--stage-art-bottom) 38%,
var(--stage-night-base-bottom)
);
--stage-night-highlight: var(--stage-art-highlight);
--stage-night-secondary: color-mix(
in oklch,
var(--stage-art-secondary) 55%,
var(--stage-night-mid)
);
--stage-night-tertiary: color-mix(
in oklch,
var(--stage-art-tertiary) 60%,
var(--stage-night-top)
);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, oklch(1 0 0));
}
:is(
html[data-theme-id="t3-chat"],
html[data-theme-id="grove"],
html[data-theme-id="ocean"],
html[data-theme-id="ember"],
html[data-theme-id="iris"]
) {
--stage-art-celeste-highlight: var(--stage-art-highlight);
--stage-art-celeste-secondary: var(--stage-art-secondary);
--stage-art-violet-highlight: var(--stage-art-highlight);
--stage-art-grid-line: var(--stage-art-line);
--stage-night-glow-highlight: var(--stage-night-highlight);
--stage-night-glow-secondary: var(--stage-night-secondary);
--stage-night-sparkle: var(--stage-night-line);
}
.workspace-topbar {
display: flex;
height: var(--workspace-topbar-height);
+11 -1
View File
@@ -60,6 +60,7 @@ import {
PullRequestFiltersMenu,
PullRequestSearchInput,
pullRequestHostLabel,
pullRequestProjectKey,
type PullRequestExpectedHost,
type PullRequestFilterOption,
} from "../components/pullRequest/PullRequestListFilters";
@@ -1250,7 +1251,16 @@ function PullRequestsRouteView() {
/** Reported per project rather than as a count, so the reader can see which one it was. */
const unavailableProjects = useMemo(
() => new Map(listErrors.map((error) => [error.projectId, error.message] as const)),
() =>
new Map(
listErrors.map(
(error) =>
[
pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
error.message,
] as const,
),
),
[listErrors],
);
@@ -59,6 +59,16 @@ describe("requestLatencyState", () => {
expect(getSlowRpcAckRequests()).toEqual([]);
});
it.each(Object.values(WS_METHODS).filter((method) => method.startsWith("pullRequests.")))(
"ignores pull request workspace request %s",
(method) => {
trackRpcRequestSent("1", method);
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS * 2);
expect(getSlowRpcAckRequests()).toEqual([]);
},
);
it("keeps ignoring untracked methods when a display tag is supplied", () => {
trackRpcRequestSent(
"1",
+5 -1
View File
@@ -49,7 +49,11 @@ function getSlowRpcAckRequestsValue(): ReadonlyArray<SlowRpcAckRequest> {
}
function shouldTrackRpcAck(method: string): boolean {
return !method.includes("subscribe") && !untrackedRpcAckMethods.has(method);
return (
!method.includes("subscribe") &&
!method.startsWith("pullRequests.") &&
!untrackedRpcAckMethods.has(method)
);
}
function rpcAckThresholdMs(method: string): number {
+8
View File
@@ -268,6 +268,14 @@ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId):
);
}
/** Whether the environment server owns synchronized thread read state. */
export function readEnvironmentSupportsViewStatus(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadViewStatus === true
);
}
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
}
+3 -1
View File
@@ -15,7 +15,6 @@ import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
import { environmentSnapshotAtom } from "./shell";
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime);
export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
environmentThreads.stateAtom,
@@ -24,6 +23,9 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: environmentSnapshotAtom,
});
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime, {
threadShellAtom: environmentThreadShells.threadShellAtom,
});
const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
Atom.withLabel("web-environment-thread:empty"),
+1 -41
View File
@@ -3,8 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
import {
legacyProjectCwdPreferenceKey,
markThreadUnread,
markThreadVisited,
parsePersistedState,
PERSISTED_STATE_KEY,
type PersistedUiState,
@@ -21,7 +19,6 @@ function makeUiState(overrides: Partial<UiState> = {}): UiState {
return {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
threadChangedFilesExpandedById: {},
defaultAdvertisedEndpointKey: null,
...overrides,
@@ -29,30 +26,6 @@ function makeUiState(overrides: Partial<UiState> = {}): UiState {
}
describe("uiStateStore pure functions", () => {
it("stores server timestamps without moving visit state backwards", () => {
const threadId = ThreadId.make("thread-1");
const initialState = makeUiState();
const visited = markThreadVisited(initialState, threadId, "2026-02-25T12:30:00.700Z");
expect(visited.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:30:00.700Z");
expect(markThreadVisited(visited, threadId, "2026-02-25T12:30:00.000Z")).toBe(visited);
expect(markThreadVisited(visited, threadId, "not-a-date")).toBe(visited);
});
it("marks a completed thread unread using the server completion timestamp", () => {
const threadId = ThreadId.make("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, "2026-02-25T12:30:00.000Z");
expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z");
expect(markThreadUnread(next, threadId, null)).toBe(next);
});
it("resolves project expansion from logical, physical, and legacy preference keys", () => {
const physicalKey = "environment:/repo/project";
const legacyKey = legacyProjectCwdPreferenceKey("/repo/project");
@@ -154,10 +127,6 @@ describe("parsePersistedState", () => {
invalid: "no" as unknown as boolean,
},
projectOrder: ["physical-b", "", "physical-a", "physical-b"],
threadLastVisitedAtById: {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
invalid: "not-a-date",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
@@ -173,9 +142,6 @@ describe("parsePersistedState", () => {
logical: false,
},
projectOrder: ["physical-b", "physical-a"],
threadLastVisitedAtById: {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpandedById: {
"environment:thread-1": {
@@ -264,15 +230,12 @@ describe("uiStateStore persistence", () => {
vi.unstubAllGlobals();
});
it("persists raw UI preferences including thread visit markers", () => {
it("persists raw UI preferences", () => {
const state = makeUiState({
projectExpandedById: {
logical: false,
},
projectOrder: ["physical-b", "physical-a"],
threadLastVisitedAtById: {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
},
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
@@ -292,9 +255,6 @@ describe("uiStateStore persistence", () => {
logical: false,
},
projectOrder: ["physical-b", "physical-a"],
threadLastVisitedAtById: {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
-74
View File
@@ -20,7 +20,6 @@ const LEGACY_PERSISTED_STATE_KEYS = [
export interface PersistedUiState {
projectExpandedById?: Record<string, boolean>;
projectOrder?: string[];
threadLastVisitedAtById?: Record<string, string>;
collapsedProjectCwds?: string[];
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
@@ -35,7 +34,6 @@ export interface UiProjectState {
}
export interface UiThreadState {
threadLastVisitedAtById: Record<string, string>;
threadChangedFilesExpandedById: Record<string, Record<string, boolean>>;
}
@@ -48,7 +46,6 @@ export interface UiState extends UiProjectState, UiThreadState, UiEndpointState
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
threadChangedFilesExpandedById: {},
defaultAdvertisedEndpointKey: null,
};
@@ -83,21 +80,6 @@ function sanitizeBooleanRecord(value: unknown): Record<string, boolean> {
);
}
function sanitizeTimestampRecord(value: unknown): Record<string, string> {
if (!value || typeof value !== "object") {
return {};
}
return Object.fromEntries(
Object.entries(value).filter(
(entry): entry is [string, string] =>
entry[0].length > 0 &&
typeof entry[1] === "string" &&
entry[1].length > 0 &&
Number.isFinite(Date.parse(entry[1])),
),
);
}
export function parsePersistedState(parsed: PersistedUiState): UiState {
const projectExpandedById =
parsed.projectExpandedById === undefined
@@ -125,7 +107,6 @@ export function parsePersistedState(parsed: PersistedUiState): UiState {
return {
projectExpandedById,
projectOrder,
threadLastVisitedAtById: sanitizeTimestampRecord(parsed.threadLastVisitedAtById),
threadChangedFilesExpandedById:
parsed.threadChangedFilesExpansionVersion === THREAD_CHANGED_FILES_EXPANSION_VERSION
? sanitizePersistedThreadChangedFilesExpanded(parsed.threadChangedFilesExpandedById)
@@ -203,7 +184,6 @@ export function persistState(state: UiState): void {
JSON.stringify({
projectExpandedById,
projectOrder: state.projectOrder,
threadLastVisitedAtById: state.threadLastVisitedAtById,
defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey,
threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION,
threadChangedFilesExpandedById: state.threadChangedFilesExpandedById,
@@ -222,54 +202,6 @@ export function persistState(state: UiState): void {
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
export function markThreadVisited(state: UiState, threadId: string, visitedAt: string): UiState {
const visitedAtMs = Date.parse(visitedAt);
if (!Number.isFinite(visitedAtMs)) {
return state;
}
const previousVisitedAt = state.threadLastVisitedAtById[threadId];
const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: visitedAt,
},
};
}
export function markThreadUnread(
state: UiState,
threadId: string,
latestTurnCompletedAt: string | null | undefined,
): UiState {
if (!latestTurnCompletedAt) {
return state;
}
const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return state;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: unreadVisitedAt,
},
};
}
export function setThreadChangedFilesExpanded(
state: UiState,
threadId: string,
@@ -382,8 +314,6 @@ export function reorderProjects(
}
interface UiStateStore extends UiState {
markThreadVisited: (threadId: string, visitedAt: string) => void;
markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;
setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;
setDefaultAdvertisedEndpointKey: (key: string | null) => void;
setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void;
@@ -396,10 +326,6 @@ interface UiStateStore extends UiState {
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
setThreadChangedFilesExpanded: (threadId, turnId, expanded) =>
set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),
setDefaultAdvertisedEndpointKey: (key) =>
@@ -24,6 +24,8 @@ import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
archiveThread,
createProject,
markThreadUnread,
markThreadViewed,
settleThread,
stopThreadSession,
unsettleThread,
@@ -171,4 +173,39 @@ describe("environment commands", () => {
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("dispatches server-owned thread view-status commands", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
yield* markThreadViewed({
commandId: CommandId.make("viewed-command"),
threadId: ThreadId.make("thread-1"),
viewedAt: "2026-08-07T12:00:00.000Z",
expectedLastViewedAt: null,
supersededViewedAt: null,
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
yield* markThreadUnread({
commandId: CommandId.make("unread-command"),
threadId: ThreadId.make("thread-1"),
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.mark-viewed",
commandId: "viewed-command",
threadId: "thread-1",
viewedAt: "2026-08-07T12:00:00.000Z",
expectedLastViewedAt: null,
supersededViewedAt: null,
},
{
type: "thread.mark-unread",
commandId: "unread-command",
threadId: "thread-1",
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
});
@@ -35,6 +35,8 @@ export type CreateThreadInput = CommandInput<"thread.create">;
export type DeleteThreadInput = CommandInput<"thread.delete">;
export type ArchiveThreadInput = CommandInput<"thread.archive">;
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
export type MarkThreadViewedInput = CommandInput<"thread.mark-viewed">;
export type MarkThreadUnreadInput = CommandInput<"thread.mark-unread">;
export type SettleThreadInput = CommandInput<"thread.settle">;
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
@@ -160,6 +162,26 @@ export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = E
});
});
export const markThreadViewed: (input: MarkThreadViewedInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.markThreadViewed",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.mark-viewed",
commandId: yield* commandId(input),
});
});
export const markThreadUnread: (input: MarkThreadUnreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.markThreadUnread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.mark-unread",
commandId: yield* commandId(input),
});
});
export const settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.settleThread",
)(function* (input) {
@@ -1,5 +1,6 @@
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import { Atom } from "effect/unstable/reactivity";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
import {
@@ -7,6 +8,8 @@ import {
type CreateThreadInput,
type DeleteThreadInput,
type InterruptThreadTurnInput,
type MarkThreadUnreadInput,
type MarkThreadViewedInput as DispatchMarkThreadViewedInput,
type RespondToThreadApprovalInput,
type RespondToThreadUserInputInput,
type RevertThreadCheckpointInput,
@@ -27,6 +30,8 @@ import {
createThread,
deleteThread,
interruptThreadTurn,
markThreadUnread,
markThreadViewed,
respondToThreadApproval,
respondToThreadUserInput,
revertThreadCheckpoint,
@@ -45,12 +50,14 @@ import {
updateThreadMetadata,
} from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import type { EnvironmentThreadShell } from "./models.ts";
export type {
ArchiveThreadInput,
CreateThreadInput,
DeleteThreadInput,
InterruptThreadTurnInput,
MarkThreadUnreadInput,
RespondToThreadApprovalInput,
RespondToThreadUserInputInput,
RevertThreadCheckpointInput,
@@ -69,8 +76,18 @@ export type {
UpdateThreadMetadataInput,
} from "../operations/commands.ts";
export type MarkThreadViewedInput = Omit<
DispatchMarkThreadViewedInput,
"expectedLastViewedAt" | "supersededViewedAt"
> & {
readonly expectedLastViewedAt?: DispatchMarkThreadViewedInput["expectedLastViewedAt"];
};
export function createThreadEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,
options: {
readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
},
) {
const scheduler = createAtomCommandScheduler();
const concurrency = {
@@ -78,6 +95,49 @@ export function createThreadEnvironmentAtoms<R, E>(
key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
JSON.stringify([environmentId, input.threadId]),
};
const queuedViewedAtByThread = new Map<string, string>();
const dispatchMarkViewed = createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:mark-viewed",
execute: (input: DispatchMarkThreadViewedInput) => markThreadViewed(input),
scheduler,
concurrency,
});
const markViewed = {
label: dispatchMarkViewed.label,
run: (
registry: AtomRegistry.AtomRegistry,
target: { readonly environmentId: EnvironmentId; readonly input: MarkThreadViewedInput },
) => {
const { expectedLastViewedAt: expectedOverride, ...input } = target.input;
const threadKey = JSON.stringify([target.environmentId, input.threadId]);
const supersededViewedAt = queuedViewedAtByThread.get(threadKey) ?? null;
if (
supersededViewedAt === null ||
Date.parse(input.viewedAt) > Date.parse(supersededViewedAt)
) {
queuedViewedAtByThread.set(threadKey, input.viewedAt);
}
const expectedLastViewedAt =
expectedOverride !== undefined
? expectedOverride
: (registry.get(
options.threadShellAtom({
environmentId: target.environmentId,
threadId: input.threadId,
}),
)?.lastViewedAt ?? null);
return dispatchMarkViewed
.run(registry, {
environmentId: target.environmentId,
input: { ...input, expectedLastViewedAt, supersededViewedAt },
})
.finally(() => {
if (queuedViewedAtByThread.get(threadKey) === input.viewedAt) {
queuedViewedAtByThread.delete(threadKey);
}
});
},
};
return {
create: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:create",
@@ -103,6 +163,13 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
markViewed,
markUnread: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:mark-unread",
execute: (input: MarkThreadUnreadInput) => markThreadUnread(input),
scheduler,
concurrency,
}),
settle: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:settle",
execute: (input: SettleThreadInput) => settleThread(input),
@@ -59,6 +59,7 @@ export function mergeEnvironmentThread(
archivedAt: shell.archivedAt,
settledOverride: shell.settledOverride,
settledAt: shell.settledAt,
lastViewedAt: shell.lastViewedAt,
snoozedUntil: shell.snoozedUntil,
snoozedAt: shell.snoozedAt,
pinnedAt: shell.pinnedAt,
@@ -231,6 +231,25 @@ describe("applyThreadDetailEvent", () => {
});
});
it("applies synchronized thread view status without changing updatedAt", () => {
const lastViewedAt = "2026-04-01T06:30:00.000Z";
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 7,
occurredAt: lastViewedAt,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.view-status-updated",
payload: { threadId: ThreadId.make("thread-1"), lastViewedAt },
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.lastViewedAt).toBe(lastViewedAt);
expect(result.thread.updatedAt).toBe(baseThread.updatedAt);
}
});
describe("thread.pinned / thread.unpinned", () => {
it("sets pinnedAt", () => {
const pinnedAt = "2026-04-01T05:00:00.000Z";
@@ -92,6 +92,7 @@ export function applyThreadDetailEvent(
archivedAt: null,
settledOverride: null,
settledAt: null,
lastViewedAt: event.payload.lastViewedAt ?? null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
@@ -123,6 +124,12 @@ export function applyThreadDetailEvent(
thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt },
};
case "thread.view-status-updated":
return {
kind: "updated",
thread: { ...thread, lastViewedAt: event.payload.lastViewedAt },
};
case "thread.settled":
return {
kind: "updated",
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
canSettle,
changeRequestAutoSettles,
effectiveSettled,
hasQueuedTurnStart,
threadLastActivityAt,
@@ -19,6 +20,18 @@ const NOW = "2026-04-10T00:00:00.000Z";
const FRESH = "2026-04-09T00:00:00.000Z";
const STALE = "2026-04-06T23:59:59.999Z";
describe("changeRequestAutoSettles", () => {
it.each([
["open", true, false],
["merged", true, true],
["merged", false, false],
["closed", false, true],
[null, false, false],
] as const)("state=%s autoSettleOnMerge=%s returns %s", (state, autoSettleOnMerge, expected) => {
expect(changeRequestAutoSettles(state, autoSettleOnMerge)).toBe(expected);
});
});
function makeShell(input: {
readonly settledOverride?: "settled" | "active" | null;
readonly activityAt: string | null;
@@ -178,6 +191,27 @@ describe("effectiveSettled", () => {
}
});
it("can keep a merged change request active", () => {
const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
expect(
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
changeRequestState: "merged",
}),
).toBe(false);
expect(
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
changeRequestState: "closed",
}),
).toBe(true);
});
it("never auto-settles a stale thread with an open change request", () => {
const stale = makeShell({ activityAt: STALE });
expect(
@@ -3,6 +3,14 @@ import type { OrchestrationThreadShell } from "@t3tools/contracts";
export type ChangeRequestStateLike = "open" | "closed" | "merged";
/** Returns whether the change request state settles the thread immediately. */
export function changeRequestAutoSettles(
state: ChangeRequestStateLike | null | undefined,
autoSettleOnMerge = true,
): boolean {
return state === "closed" || (state === "merged" && autoSettleOnMerge);
}
const DAY_MS = 24 * 60 * 60 * 1_000;
export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
@@ -183,7 +191,7 @@ export function effectiveSnoozed(
* still snoozed. Used for the "Woke" indicator: the thread reappears in its
* original sort position (the inbox sort is deliberately static), so the
* wake signal has to carry the weight. Compare against the client's
* lastVisitedAt — visiting clears the indicator like it clears unread.
* server-owned lastViewedAt — viewing clears the indicator like it clears unread.
*
* Timer wakes report the wake time itself; raised-hand wakes report the
* triggering timestamp so a visit BEFORE the early wake doesn't suppress
@@ -199,7 +207,7 @@ export function threadWokeAt(
// An early hand-raise wake stays authoritative even after the scheduled
// wake time passes: reporting snoozedUntil then would resurface a Woke
// indicator the user already cleared by visiting (snoozedUntil is newer
// than that visit's lastVisitedAt).
// than that view's lastViewedAt).
if (threadRaisedHandWhileSnoozed(shell)) {
if (
shell.snoozedAt != null &&
@@ -221,9 +229,9 @@ export function threadWokeAt(
* queued turn) are checked first and hold a thread active regardless of any
* override. Past the blockers, the explicit user override (thread.settle /
* thread.unsettle commands, projected into settledOverride + settledAt)
* wins in both directions; without one, a thread auto-settles on a
* merged/closed PR immediately or on inactivity past the window — except
* that an open PR blocks the inactivity path entirely. The server
* wins in both directions; without one, a thread can auto-settle on a
* merged PR, always settles on a closed PR, or settles on inactivity past
* the window. An open PR blocks the inactivity path entirely. The server
* un-settles on real activity (user message, session start, approval/
* user-input request), so an override never goes stale silently.
*/
@@ -232,6 +240,7 @@ export function effectiveSettled(
options: {
readonly now: string;
readonly autoSettleAfterDays: number | null;
readonly autoSettleOnMerge?: boolean;
readonly changeRequestState?: ChangeRequestStateLike | null;
},
): boolean {
@@ -258,13 +267,13 @@ export function effectiveSettled(
// "active" is the explicit keep-active pin: it suppresses auto-settle
// until real activity clears it server-side.
if (shell.settledOverride === "active") return false;
if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
if (changeRequestAutoSettles(options.changeRequestState, options.autoSettleOnMerge !== false)) {
return true;
}
// An open PR is unfinished business regardless of how long the thread has
// been quiet: review can take days, and hiding the thread would bury the
// work waiting on it. Only merge/close (above) or an explicit user settle
// resolves it.
// work waiting on it. A configured merge, a close, or an explicit user
// settle resolves it.
if (options.changeRequestState === "open") return false;
if (options.autoSettleAfterDays === null) return false;
+3
View File
@@ -64,6 +64,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server understands thread.pin.reorder (and orderKey on thread.pin).
Same version-skew contract as threadSettlement. */
threadPinReorder: Schema.optionalKey(Schema.Boolean),
/** Server owns thread read/unread state and understands
thread.mark-viewed / thread.mark-unread commands. */
threadViewStatus: Schema.optionalKey(Schema.Boolean),
/** Server understands regenerateTitle on thread.meta.update. Absent on
older servers, so clients hide the action instead of sending it. */
threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
+41
View File
@@ -380,6 +380,9 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
// Optional so threads from servers predating synchronized read state still decode.
// Missing means read-by-default, avoiding an unread flood on upgrade.
lastViewedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
// Snooze is an overlay on the active lifecycle, not a fourth destination:
// a snoozed thread stays "active" in the model and is only suppressed from
// the inbox until snoozedUntil passes (or the thread raises its hand).
@@ -450,6 +453,7 @@ export const OrchestrationThreadShell = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
lastViewedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
@@ -684,6 +688,27 @@ const ThreadUnarchiveCommand = Schema.Struct({
threadId: ThreadId,
});
const ThreadMarkViewedCommand = Schema.Struct({
type: Schema.Literal("thread.mark-viewed"),
commandId: CommandId,
threadId: ThreadId,
// A boundary copied from server-owned thread state (completion or wake).
// It is not the client's wall clock.
viewedAt: IsoDateTime,
// Captured when the client queues the view, so it cannot overwrite a newer
// explicit unread action.
expectedLastViewedAt: Schema.NullOr(IsoDateTime),
// The preceding queued view boundary. This lets serialized completion views
// advance in order without treating an explicit unread as their predecessor.
supersededViewedAt: Schema.NullOr(IsoDateTime),
});
const ThreadMarkUnreadCommand = Schema.Struct({
type: Schema.Literal("thread.mark-unread"),
commandId: CommandId,
threadId: ThreadId,
});
const ThreadSettleCommand = Schema.Struct({
type: Schema.Literal("thread.settle"),
commandId: CommandId,
@@ -903,6 +928,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,
ThreadMarkViewedCommand,
ThreadMarkUnreadCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadSnoozeCommand,
@@ -931,6 +958,8 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,
ThreadMarkViewedCommand,
ThreadMarkUnreadCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadSnoozeCommand,
@@ -1049,6 +1078,7 @@ export const OrchestrationEventType = Schema.Literals([
"thread.deleted",
"thread.archived",
"thread.unarchived",
"thread.view-status-updated",
"thread.settled",
"thread.unsettled",
"thread.snoozed",
@@ -1119,6 +1149,7 @@ export const ThreadCreatedPayload = Schema.Struct({
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
lastViewedAt: Schema.optional(IsoDateTime),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
});
@@ -1139,6 +1170,11 @@ export const ThreadUnarchivedPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
export const ThreadViewStatusUpdatedPayload = Schema.Struct({
threadId: ThreadId,
lastViewedAt: IsoDateTime,
});
export const ThreadSettledPayload = Schema.Struct({
threadId: ThreadId,
settledAt: IsoDateTime,
@@ -1362,6 +1398,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.unarchived"),
payload: ThreadUnarchivedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.view-status-updated"),
payload: ThreadViewStatusUpdatedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.settled"),
+11 -1
View File
@@ -68,10 +68,11 @@ describe("ClientSettings environment identification", () => {
});
describe("ClientSettings sidebar", () => {
it("defaults to the current sidebar with a three-day auto-settle threshold", () => {
it("defaults to the current sidebar with automatic merge and inactivity settling", () => {
const settings = decodeClientSettings({});
expect(settings.legacySidebarEnabled).toBe(false);
expect(settings.sidebarAutoSettleAfterDays).toBe(3);
expect(settings.sidebarAutoSettleOnMerge).toBe(true);
});
it("drops the retired sidebar v2 beta keys, resetting everyone to the default", () => {
@@ -97,6 +98,15 @@ describe("ClientSettings sidebar", () => {
).toBeNull();
});
it("allows auto-settle on merge to be disabled", () => {
expect(decodeClientSettings({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge).toBe(
false,
);
expect(
decodeClientSettingsPatch({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge,
).toBe(false);
});
it.each([-1, 0, 91])("rejects an auto-settle threshold outside 1..90: %s", (value) => {
expect(() => decodeClientSettings({ sidebarAutoSettleAfterDays: value })).toThrow();
expect(() => decodeClientSettingsPatch({ sidebarAutoSettleAfterDays: value })).toThrow();
+2
View File
@@ -180,6 +180,7 @@ export const ClientSettingsSchema = Schema.Struct({
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
),
sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
),
@@ -793,6 +794,7 @@ export const ClientSettingsPatch = Schema.Struct({
planModeEnabled: Schema.optionalKey(Schema.Boolean),
legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
sidebarProjectGroupingOverrides: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),