diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index d12d7179ef339..4cf909aa2f2da 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -92,6 +92,7 @@ import { } from "../threads/threadListV2"; import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences"; import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu"; +import { useJarvisHomeEntry } from "../jarvis/JarvisHomeEntry"; import { buildHomeProjectScopes, findHomeProjectScope, @@ -645,11 +646,15 @@ export function HomeScreen(props: HomeScreenProps) { : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ?? "this environment"); const emptyState = deriveHomeEmptyState(props.catalogState, props.projects.length, m); + const jarvisEntry = useJarvisHomeEntry(props.visible); if (!hasAnyThreads) { return ( + {jarvisEntry === null ? null : ( + {jarvisEntry} + )} + {jarvisEntry} {listHeader} {Platform.OS === "ios" && workspace ? ( + {jarvisEntry} ({ start: vi.fn(), open: vi.fn(), retry: vi.fn() })); +const environmentId = EnvironmentId.make("primary"); +const otherEnvironmentId = EnvironmentId.make("secondary"); +const threadId = ThreadId.make("today-thread"); +const day = "2026-11-30"; +const command = { id: "confirm:hash", label: "Confirm", type: "command" } as const; +const cancel = { id: "cancel:hash", label: "Cancel", type: "command" } as const; +const proposedAt = IsoDateTime.make("2026-11-30T12:00:00.000Z"); +const proposal: JarvisProposalCard = { + id: "jarvis.proposal:proposal", + threadId, + kind: "jarvis.proposal", + placement: { type: "time", at: proposedAt }, + updatedAt: proposedAt, + actions: [command, cancel], + data: { + card: { + id: "proposal", + threadId, + kind: "review-reply", + title: "Reply to a review", + source: "Review", + ask: "Send this reply?", + context: null, + options: [], + effectText: "Thanks for reviewing.", + effectHash: "a".repeat(64), + state: "proposed", + reason: null, + proposedAt, + decidedAt: null, + settledAt: null, + expiresAt: null, + outcome: null, + }, + }, +}; + +vi.mock("./jarvisState", async () => { + const { AsyncResult, Atom } = await import("effect/reactivity"); + return { + jarvisPrimaryEnvironmentIdAtom: Atom.make(null), + jarvisTodayAtomFamily: vi.fn(() => Atom.make(AsyncResult.initial())), + jarvisThreadCardsAtomFamily: vi.fn(() => Atom.make(AsyncResult.initial())), + startJarvisToday: { permissionAtom: vi.fn(() => Atom.make(false)) }, + }; +}); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => actions.start })); +vi.mock("../../state/query", async (importOriginal) => { + const query = await importOriginal(); + return { + ...query, + useEnvironmentQuery: (atom: Parameters[0]) => ({ + ...query.useEnvironmentQuery(atom), + refresh: actions.retry, + }), + }; +}); +vi.mock("../layout/workspace/useSelectWorkspaceDetail", () => ({ + useSelectWorkspaceDetail: () => actions.open, +})); +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) => createElement("div", null, children), +})); +vi.mock("../../components/ui/ListRow", () => ({ + ListRow: (props: { label: string; detail?: string; onPress: () => void }) => + createElement("button", { onClick: props.onPress }, props.label, props.detail), +})); +vi.mock("../../components/ui/ListActionRow", () => ({ + ListActionRow: (props: { + label: string; + description?: string; + disabled?: boolean; + loading?: boolean; + onPress: () => void; + }) => + createElement( + "button", + { + "aria-label": props.label, + disabled: props.disabled || props.loading, + onClick: props.onPress, + }, + props.label, + props.description, + ), +})); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ children }: { children: ReactNode }) => createElement("p", null, children), +})); + +function today(overrides: Partial = {}): JarvisToday { + return { + environmentId, + day, + today: null, + previous: [], + morning: null, + status: { availability: "ready", detail: null }, + ...overrides, + }; +} + +const target = { name: "Thread", params: { environmentId, threadId } }; + +async function renderEntry({ permitted = true, primary = environmentId } = {}) { + const atoms = await import("./jarvisState"); + const snapshot = Atom.make>(AsyncResult.initial()); + const cards = Atom.make>(AsyncResult.initial()); + const permission = Atom.make(permitted); + vi.mocked(atoms.jarvisTodayAtomFamily).mockReturnValue(snapshot); + vi.mocked(atoms.jarvisThreadCardsAtomFamily).mockReturnValue(cards); + vi.mocked(atoms.startJarvisToday.permissionAtom).mockReturnValue(permission); + const registry = AtomRegistry.make(); + const primaryAtom = atoms.jarvisPrimaryEnvironmentIdAtom as Atom.Writable; + registry.set(primaryAtom, primary); + const container = document.createElement("div"); + const root = createRoot(container); + function HomeEntry({ visible }: { readonly visible: boolean }) { + return useJarvisHomeEntry(visible); + } + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const setVisible = (visible: boolean) => + act(() => + root.render( + createElement( + RegistryContext.Provider, + { value: registry }, + createElement(HomeEntry, { visible }), + ), + ), + ); + await setVisible(true); + return { + container, + get button() { + return container.querySelector("button"); + }, + setSnapshot: (value: AsyncResult.AsyncResult) => + act(() => registry.set(snapshot, value)), + setCards: (value: PluginThreadCards) => + act(() => registry.set(cards, AsyncResult.success(value))), + setPrimary: (value: EnvironmentId | null) => act(() => registry.set(primaryAtom, value)), + setVisible, + [Symbol.dispose]() { + act(() => root.unmount()); + registry.dispose(); + }, + }; +} + +afterEach(() => { + vi.clearAllMocks(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe("mobile Jarvis Home actions", () => { + it("subscribes to the primary only, waits for the first snapshot and opens the counted thread on tap", async () => { + using entry = await renderEntry(); + const atoms = await import("./jarvisState"); + expect(atoms.jarvisTodayAtomFamily).toHaveBeenCalledWith({ environmentId, input: {} }); + expect(entry.container.textContent).toBe(""); + expect(atoms.jarvisThreadCardsAtomFamily).not.toHaveBeenCalled(); + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + expect(entry.button?.textContent).toBe("Jarvis · Mon, Nov 30"); + expect(actions.open).not.toHaveBeenCalled(); + expect(atoms.jarvisThreadCardsAtomFamily).toHaveBeenLastCalledWith({ + environmentId, + input: { threadId }, + }); + await entry.setCards({ threadId, cards: [proposal] }); + expect(entry.button?.textContent).toBe("Jarvis · Mon, Nov 301 waiting"); + await entry.setCards({ threadId, cards: [] }); + expect(entry.button?.textContent).toBe("Jarvis · Mon, Nov 30"); + await act(() => entry.button!.click()); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + await entry.setPrimary(null); + expect(entry.container.textContent).toBe(""); + }); + + it("shows the initial failure with a working retry and shows the next settled snapshot", async () => { + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.failure(Cause.die("offline"))); + expect(entry.container.textContent).toContain("I can't reach this environment right now."); + expect(entry.button?.getAttribute("aria-label")).toBe("Retry"); + await act(() => entry.button!.click()); + expect(actions.retry).toHaveBeenCalledTimes(1); + await entry.setSnapshot(AsyncResult.success(today())); + expect(entry.button?.textContent).toBe("Open today's thread"); + }); + + it.each([ + ["disabled", "Turned off.", ""], + ["not-installed", "Jarvis is missing.", "Jarvis is missing."], + ["needs-update", "Update Jarvis first.", "Update Jarvis first."], + ] as const)("has no action when availability is %s", async (availability, detail, text) => { + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today({ status: { availability, detail } }))); + expect(entry.container.textContent).toBe(text); + expect(entry.button).toBeNull(); + }); + + it("blocks a start without permission", async () => { + using entry = await renderEntry({ permitted: false }); + await entry.setSnapshot(AsyncResult.success(today())); + expect(entry.button?.textContent).toBe("Open today's thread"); + expect(entry.button?.disabled).toBe(true); + await act(() => entry.button!.click()); + expect(actions.start).not.toHaveBeenCalled(); + }); + + it.each([ + ["not-installed", "Jarvis isn't installed where this environment expects it."], + ["needs-update", "Jarvis needs updating before RuCode can use it."], + ] as const)( + "shows a reason without an action when the %s detail is null", + async (availability, reason) => { + using entry = await renderEntry(); + await entry.setSnapshot( + AsyncResult.success(today({ status: { availability, detail: null } })), + ); + expect(entry.container.textContent).toBe(reason); + expect(entry.button).toBeNull(); + }, + ); + + it.each([true, false])( + "opens the returned thread when created is %s and suppresses duplicate pending taps", + async (created) => { + const response = Promise.withResolvers(); + actions.start.mockReturnValueOnce(response.promise); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => { + entry.button!.click(); + entry.button!.click(); + }); + expect(actions.start).toHaveBeenCalledExactlyOnceWith({ environmentId, input: {} }); + expect(entry.button?.disabled).toBe(true); + expect(actions.open).not.toHaveBeenCalled(); + await act(() => response.resolve(AsyncResult.success({ created, threadId }))); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + }, + ); + + it("shows the JarvisError message below the offer and allows another attempt", async () => { + actions.start.mockResolvedValueOnce( + AsyncResult.failure( + Cause.fail(new JarvisError({ reason: "launch-failed", detail: "Claude is signed out." })), + ), + ); + actions.start.mockResolvedValueOnce(AsyncResult.success({ created: true, threadId })); + using entry = await renderEntry(); + await entry.setSnapshot( + AsyncResult.success(today({ status: { availability: "watcher-down", detail: null } })), + ); + await act(() => entry.button!.click()); + expect(entry.button?.textContent).toBe("Open today's thread"); + expect(entry.button?.nextElementSibling?.textContent).toBe( + "Today's Jarvis thread couldn't be started. Claude is signed out.", + ); + expect(actions.open).not.toHaveBeenCalled(); + await act(() => entry.button!.click()); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + }); + + it("shows an authorization denial and does not navigate when today's thread arrives independently", async () => { + actions.start.mockResolvedValueOnce( + AsyncResult.failure( + Cause.fail( + new EnvironmentAuthorizationError({ + message: "Permission was revoked.", + requiredScope: AuthOrchestrationOperateScope, + }), + ), + ), + ); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => entry.button!.click()); + expect(entry.button?.nextElementSibling?.textContent).toBe("Permission was revoked."); + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + expect(actions.open).not.toHaveBeenCalled(); + }); + + it.each(["before", "after"])( + "opens once when the thread arrives %s an unconfirmed response", + async (arrival) => { + const response = Promise.withResolvers(); + actions.start.mockReturnValueOnce(response.promise); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => entry.button!.click()); + if (arrival === "before") { + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + expect(actions.open).not.toHaveBeenCalled(); + } + await act(() => response.resolve(AsyncResult.failure(Cause.interrupt()))); + if (arrival === "after") { + expect(actions.open).not.toHaveBeenCalled(); + expect(entry.button?.textContent).toBe("Open today's thread"); + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + } + await entry.setSnapshot( + AsyncResult.success( + today({ today: threadId, status: { availability: "watcher-down", detail: null } }), + ), + ); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + }, + ); + + it("ignores a response from a primary environment that was switched away during the start", async () => { + const response = Promise.withResolvers(); + actions.start.mockReturnValueOnce(response.promise); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => entry.button!.click()); + await entry.setPrimary(otherEnvironmentId); + await act(() => response.resolve(AsyncResult.success({ created: true, threadId }))); + expect(actions.open).not.toHaveBeenCalled(); + }); + + it("opens the recovered thread when Home is visible again", async () => { + actions.start.mockResolvedValueOnce(AsyncResult.failure(Cause.interrupt())); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => entry.button!.click()); + await entry.setVisible(false); + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + expect(actions.open).not.toHaveBeenCalled(); + await entry.setVisible(true); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + }); + + it("does not navigate again when a user opened the arriving thread before the response", async () => { + const response = Promise.withResolvers(); + actions.start.mockReturnValueOnce(response.promise); + using entry = await renderEntry(); + await entry.setSnapshot(AsyncResult.success(today())); + await act(() => entry.button!.click()); + await entry.setSnapshot(AsyncResult.success(today({ today: threadId }))); + await act(() => entry.button!.click()); + await act(() => response.resolve(AsyncResult.success({ created: true, threadId }))); + expect(actions.open).toHaveBeenCalledExactlyOnceWith(target); + }); +}); diff --git a/apps/mobile/src/features/jarvis/JarvisHomeEntry.tsx b/apps/mobile/src/features/jarvis/JarvisHomeEntry.tsx new file mode 100644 index 0000000000000..d29d49706da45 --- /dev/null +++ b/apps/mobile/src/features/jarvis/JarvisHomeEntry.tsx @@ -0,0 +1,205 @@ +import { useAtomValue } from "@effect/atom-react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentAuthorizationError, + JarvisError, + type EnvironmentId, + type ThreadId, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useGT, useLocale } from "gt-react-native"; +import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react"; +import { View } from "react-native"; + +import { AppText } from "../../components/ui/AppText"; +import { ListActionRow } from "../../components/ui/ListActionRow"; +import { ListRow } from "../../components/ui/ListRow"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; +import { formatJarvisDay, jarvisEntryView, jarvisWaitingCount } from "./jarvisEntry.logic"; +import { + jarvisPrimaryEnvironmentIdAtom, + jarvisThreadCardsAtomFamily, + jarvisTodayAtomFamily, + startJarvisToday, +} from "./jarvisState"; + +const NO_START_PERMISSION = Atom.make(false); +const isJarvisError = Schema.is(JarvisError); +const isAuthorizationError = Schema.is(EnvironmentAuthorizationError); + +type StartAttempt = { readonly environmentId: EnvironmentId } & ( + | { readonly kind: "pending" | "unconfirmed" } + | { readonly kind: "confirmed"; readonly threadId: ThreadId } + | { readonly kind: "rejected"; readonly message: string } +); + +function JarvisHomeEntry({ + children, + message, +}: { + readonly children: ReactNode; + readonly message: string | null; +}) { + return ( + + {children} + {message === null ? null : ( + + {message} + + )} + + ); +} + +function JarvisOpenRow(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly day: string; + readonly onPress: () => void; +}) { + const gt = useGT(); + const locale = useLocale(); + const count = useAtomValue( + jarvisThreadCardsAtomFamily({ + environmentId: props.environmentId, + input: { threadId: props.threadId }, + }), + (result) => jarvisWaitingCount(AsyncResult.getOrElse(result, () => null)?.cards ?? []), + ); + return ( + + ); +} + +export function useJarvisHomeEntry(visible: boolean) { + const gt = useGT(); + const selectDetail = useSelectWorkspaceDetail(); + const environmentId = useAtomValue(jarvisPrimaryEnvironmentIdAtom); + const today = useEnvironmentQuery( + environmentId === null ? null : jarvisTodayAtomFamily({ environmentId, input: {} }), + ); + const view = jarvisEntryView(today.data, today.error); + const threadId = view.kind === "open" ? view.threadId : null; + const canStart = useAtomValue( + environmentId === null ? NO_START_PERMISSION : startJarvisToday.permissionAtom(environmentId), + ); + const start = useAtomCommand(startJarvisToday, { reportFailure: false }); + const [attempt, setAttempt] = useState(null); + const pending = useRef(new Set()); + if (attempt !== null && attempt.environmentId !== environmentId) setAttempt(null); + const activeAttempt = attempt?.environmentId === environmentId ? attempt : null; + const openedThreadId = + activeAttempt?.kind === "confirmed" + ? activeAttempt.threadId + : activeAttempt?.kind === "unconfirmed" + ? threadId + : null; + + const [navigation, setNavigation] = useState<{ + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + } | null>(null); + if (visible && environmentId !== null && openedThreadId !== null) { + setNavigation({ environmentId, threadId: openedThreadId }); + setAttempt(null); + } + const openThread = useEffectEvent((target: NonNullable) => { + selectDetail({ name: "Thread", params: target }); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the native route once per resolved start + useEffect(() => { + if (navigation !== null) openThread(navigation); + }, [navigation]); + + if (environmentId === null || view.kind === "hidden") return null; + + const openToday = async () => { + if (!canStart || pending.current.has(environmentId)) return; + pending.current.add(environmentId); + const started = { kind: "pending", environmentId } as const; + setAttempt(started); + const result = await start({ environmentId, input: {} }); + pending.current.delete(environmentId); + if (result._tag === "Success") { + setAttempt((current) => + current === started + ? { kind: "confirmed", environmentId, threadId: result.value.threadId } + : current, + ); + return; + } + const error = squashAtomCommandFailure(result); + setAttempt((current) => { + if (current !== started) return current; + return isJarvisError(error) || isAuthorizationError(error) + ? { kind: "rejected", environmentId, message: error.message } + : { kind: "unconfirmed", environmentId }; + }); + }; + + const message = + activeAttempt?.kind === "rejected" + ? activeAttempt.message + : activeAttempt?.kind === "unconfirmed" && threadId === null + ? gt("I couldn't confirm that today's thread opened.") + : null; + + let row: ReactNode; + switch (view.kind) { + case "open": + row = ( + { + setAttempt(null); + selectDetail({ name: "Thread", params: { environmentId, threadId: view.threadId } }); + }} + /> + ); + break; + case "can-start": + row = ( + void openToday()} + /> + ); + break; + case "unavailable": + row = ( + + {view.detail ?? + (today.data?.status.availability === "needs-update" + ? gt("Jarvis needs updating before RuCode can use it.") + : gt("Jarvis isn't installed where this environment expects it."))} + + ); + break; + case "failed": + row = ( + + ); + break; + } + return {row}; +} diff --git a/apps/mobile/src/features/jarvis/jarvisEntry.logic.test.ts b/apps/mobile/src/features/jarvis/jarvisEntry.logic.test.ts new file mode 100644 index 0000000000000..8601fc15c7f43 --- /dev/null +++ b/apps/mobile/src/features/jarvis/jarvisEntry.logic.test.ts @@ -0,0 +1,175 @@ +import { EnvironmentId, ThreadId, type JarvisToday } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + formatJarvisDay, + jarvisEntryView, + jarvisRuntimeIsReadOnly, + jarvisWaitingCount, + primaryJarvisEnvironmentId, +} from "./jarvisEntry.logic"; + +const environmentId = EnvironmentId.make("primary"); +const otherEnvironmentId = EnvironmentId.make("secondary"); +const threadId = ThreadId.make("today-thread"); +const otherThreadId = ThreadId.make("different-thread"); +const day = "2026-11-30"; +const command = { id: "confirm:hash", label: "Confirm", type: "command" } as const; +const cancel = { id: "cancel:hash", label: "Cancel", type: "command" } as const; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function today(overrides: Partial = {}): JarvisToday { + return { + environmentId, + day, + today: null, + previous: [], + morning: null, + status: { availability: "ready", detail: null }, + ...overrides, + }; +} + +function primaryEntry(environment: EnvironmentId, enabled = true, primary = false) { + return [ + environment, + { enabled, target: { _tag: primary ? "PrimaryConnectionTarget" : "BearerConnectionTarget" } }, + ] as const; +} + +describe("mobile Jarvis entry views", () => { + it("hides only while no value or error has arrived", () => { + expect(jarvisEntryView(null, null)).toEqual({ kind: "hidden" }); + }); + + it("shows a failure when the first snapshot is missing and a stream error has arrived", () => { + expect(jarvisEntryView(null, "offline")).toEqual({ kind: "failed" }); + }); + + it("keeps the last thread visible after a stream error, using today rather than a previous day", () => { + expect( + jarvisEntryView( + today({ + today: threadId, + previous: [{ day: "2026-11-29", threadId: otherThreadId }], + }), + "offline", + ), + ).toEqual({ kind: "open", threadId, day }); + }); + + it.each([ + ["ready", null], + ["watcher-down", "The watcher isn't running."], + ] as const)( + "offers a start when today is null and availability is %s", + (availability, detail) => { + expect(jarvisEntryView(today({ status: { availability, detail } }), null)).toEqual({ + kind: "can-start", + detail, + }); + }, + ); + + it("hides disabled Jarvis even if a snapshot carries a thread", () => { + expect( + jarvisEntryView( + today({ + today: threadId, + status: { availability: "disabled", detail: "Turned off." }, + }), + null, + ), + ).toEqual({ kind: "hidden" }); + }); + + it.each([ + ["not-installed", "Jarvis is missing from this environment."], + ["needs-update", "This version is too old."], + ] as const)("exposes the supplied %s reason", (availability, detail) => { + expect(jarvisEntryView(today({ status: { availability, detail } }), null)).toEqual({ + kind: "unavailable", + detail, + }); + }); +}); + +describe("mobile Jarvis row data", () => { + it("returns no environment when there are no enabled connections", () => { + expect(primaryJarvisEnvironmentId(new Map())).toBeNull(); + expect(primaryJarvisEnvironmentId(new Map([primaryEntry(environmentId, false)]))).toBeNull(); + }); + + it("uses the explicit primary regardless of connection order", () => { + expect( + primaryJarvisEnvironmentId( + new Map([primaryEntry(otherEnvironmentId), primaryEntry(environmentId, true, true)]), + ), + ).toBe(environmentId); + }); + + it("uses the first enabled connection in catalog order when mobile has only saved connections", () => { + expect( + primaryJarvisEnvironmentId( + new Map([ + primaryEntry(EnvironmentId.make("disabled"), false), + primaryEntry(environmentId), + primaryEntry(otherEnvironmentId), + ]), + ), + ).toBe(environmentId); + }); + + it("counts zero before any proposal with actions", () => { + expect(jarvisWaitingCount([])).toBe(0); + expect(jarvisWaitingCount([{ kind: "jarvis.proposal", actions: [] }])).toBe(0); + }); + + it("counts each Jarvis proposal once, including one action, and ignores other card kinds", () => { + expect( + jarvisWaitingCount([ + { kind: "jarvis.proposal", actions: [command, cancel] }, + { kind: "jarvis.proposal", actions: [cancel] }, + { kind: "dispatch.decision", actions: [command] }, + { kind: "jarvis.proposal", actions: [] }, + ]), + ).toBe(2); + }); + + it("formats the date with the selected locale and UTC", () => { + const formatter = vi.spyOn(Intl, "DateTimeFormat"); + expect(formatJarvisDay(day, "en-US")).toBe("Mon, Nov 30"); + expect(formatJarvisDay(day, "fr-FR")).toBe("lun. 30 nov."); + expect(formatter).toHaveBeenCalledWith("en-US", expect.objectContaining({ timeZone: "UTC" })); + }); + + it.each(["", "invalid", "2026-02-29", "2026-11-31", "2026-13-01"])( + "preserves the raw day when %j is not a calendar date", + (value) => expect(formatJarvisDay(value, "en-US")).toBe(value), + ); + + it("formats a leap day and the first day of a year", () => { + expect(formatJarvisDay("2024-02-29", "en-US")).toBe("Thu, Feb 29"); + expect(formatJarvisDay("2026-01-01", "en-US")).toBe("Thu, Jan 1"); + }); +}); + +describe("mobile Jarvis Runtime settings", () => { + it("makes today's and earlier tagged Jarvis threads read-only", () => { + expect(jarvisRuntimeIsReadOnly({ tags: ["jarvis", "jarvis:2026-11-30"] }, undefined)).toBe( + true, + ); + expect(jarvisRuntimeIsReadOnly({}, { tags: ["jarvis", "jarvis:2026-11-29"] })).toBe(true); + }); + + it("keeps ordinary threads editable with missing or unrelated tags", () => { + expect(jarvisRuntimeIsReadOnly({}, undefined)).toBe(false); + expect(jarvisRuntimeIsReadOnly({ tags: ["jarvis:2026-11-30", "jarvis-like"] }, undefined)).toBe( + false, + ); + expect(jarvisRuntimeIsReadOnly({ tags: ["jarvis"] }, {})).toBe(false); + }); +}); diff --git a/apps/mobile/src/features/jarvis/jarvisEntry.logic.ts b/apps/mobile/src/features/jarvis/jarvisEntry.logic.ts new file mode 100644 index 0000000000000..1a4cd1834b92a --- /dev/null +++ b/apps/mobile/src/features/jarvis/jarvisEntry.logic.ts @@ -0,0 +1,60 @@ +import { + isJarvisThread, + type EnvironmentId, + type JarvisToday, + type PluginCard, + type ThreadId, +} from "@t3tools/contracts"; + +type JarvisEntryView = + | { readonly kind: "hidden" | "failed" } + | { readonly kind: "open"; readonly threadId: ThreadId; readonly day: string } + | { readonly kind: "can-start" | "unavailable"; readonly detail: string | null }; + +export function jarvisEntryView(data: JarvisToday | null, error: string | null): JarvisEntryView { + if (data === null) return { kind: error === null ? "hidden" : "failed" }; + const { availability, detail } = data.status; + if (availability === "disabled") return { kind: "hidden" }; + if (data.today !== null) return { kind: "open", threadId: data.today, day: data.day }; + return availability === "ready" || availability === "watcher-down" + ? { kind: "can-start", detail } + : { kind: "unavailable", detail }; +} + +export function jarvisWaitingCount(cards: ReadonlyArray>) { + return cards.filter((card) => card.kind === "jarvis.proposal" && card.actions.length > 0).length; +} + +export function formatJarvisDay(day: string, locale: string): string { + if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return day; + const date = new Date(`${day}T00:00:00Z`); + if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== day) return day; + return new Intl.DateTimeFormat(locale, { + weekday: "short", + month: "short", + day: "numeric", + timeZone: "UTC", + }).format(date); +} + +export function jarvisRuntimeIsReadOnly( + shell: Parameters[0], + detail: Parameters[0] | undefined, +): boolean { + return isJarvisThread(detail ?? shell); +} + +export function primaryJarvisEnvironmentId( + entries: ReadonlyMap< + EnvironmentId, + { readonly enabled: boolean; readonly target: { readonly _tag: string } } + >, +): EnvironmentId | null { + let firstEnabled: EnvironmentId | null = null; + for (const [id, entry] of entries) { + if (!entry.enabled) continue; + if (entry.target._tag === "PrimaryConnectionTarget") return id; + firstEnabled ??= id; + } + return firstEnabled; +} diff --git a/apps/mobile/src/features/jarvis/jarvisState.ts b/apps/mobile/src/features/jarvis/jarvisState.ts new file mode 100644 index 0000000000000..3e09fa04d982b --- /dev/null +++ b/apps/mobile/src/features/jarvis/jarvisState.ts @@ -0,0 +1,29 @@ +import { + createEnvironmentRpcCommand, + createEnvironmentRpcSubscriptionAtomFamily, +} from "@t3tools/client-runtime/state/runtime"; +import { WS_METHODS } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { environmentCatalog } from "../../connection/catalog"; +import { connectionAtomRuntime } from "../../connection/runtime"; +import { primaryJarvisEnvironmentId } from "./jarvisEntry.logic"; + +export const jarvisPrimaryEnvironmentIdAtom = environmentCatalog.catalogValueAtom.pipe( + Atom.map((catalog) => primaryJarvisEnvironmentId(catalog.entries)), +); + +export const jarvisTodayAtomFamily = createEnvironmentRpcSubscriptionAtomFamily( + connectionAtomRuntime, + { label: "mobile:jarvis-today", tag: WS_METHODS.jarvisSubscribeToday }, +); + +export const startJarvisToday = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "mobile:start-jarvis-today", + tag: WS_METHODS.jarvisStartToday, +}); + +export const jarvisThreadCardsAtomFamily = createEnvironmentRpcSubscriptionAtomFamily( + connectionAtomRuntime, + { label: "mobile:jarvis-thread-cards", tag: WS_METHODS.pluginCardsSubscribeThread }, +); diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 36949d6cf9440..a32c1eb455781 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -5,6 +5,7 @@ import { import { T, useGT, useLocale, useMessages } from "gt-react-native"; import * as Dialog from "../../components/ui/Dialog"; import { createV5StackNavigator as createNativeStackNavigator } from "../../native/createV5StackNavigator"; +import { jarvisRuntimeIsReadOnly } from "../jarvis/jarvisEntry.logic"; import { useSheetStackOptions } from "../layout/nested-stacks"; import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts"; import { @@ -232,15 +233,18 @@ function ProviderHeader(props: { function DisclosureRow(props: { readonly label: string; readonly value: string | undefined; - readonly onPress: () => void; + readonly onPress?: (() => void) | undefined; readonly isLast?: boolean; }) { + const Row = props.onPress === undefined ? View : Pressable; return ( - ) : null} - - + {props.onPress === undefined ? null : ( + + )} + ); } @@ -305,6 +311,7 @@ type ThreadSettingsSessionProps = { readonly optionDescriptors: ReadonlyArray; readonly onUpdateOptionSelections: (selections: ReadonlyArray) => void; readonly runtimeMode: RuntimeMode; + readonly runtimeReadOnly?: boolean; readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void; }; @@ -327,6 +334,7 @@ type ThreadSettingsSessionValue = { readonly manageHidden: boolean; readonly setManageHidden: (value: boolean) => void; readonly runtimeMode: RuntimeMode; + readonly runtimeReadOnly: boolean; readonly runtimeModeChoices: ReadonlyArray; readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void; readonly displayedDescriptors: ReadonlyArray; @@ -662,6 +670,7 @@ function ThreadSettingsSessionProvider( toggleHidden, pendingHiddenKeys, runtimeMode: compatibleRuntimeMode, + runtimeReadOnly: props.runtimeReadOnly ?? false, runtimeModeChoices, onUpdateRuntimeMode: props.onUpdateRuntimeMode, displayedDescriptors, @@ -1117,12 +1126,15 @@ function ThreadSettingsOptionsItem(props: { isLast label={gt("Runtime", { $context: "agent permission mode setting" })} value={(() => { + if (session.runtimeReadOnly) return gt("Read and propose"); const label = session.runtimeModeChoices.find( (choice) => choice.mode === session.runtimeMode, )?.label; return label === undefined ? undefined : m(label); })()} - onPress={() => props.onOpenSubmenu({ kind: "runtime" })} + onPress={ + session.runtimeReadOnly ? undefined : () => props.onOpenSubmenu({ kind: "runtime" }) + } /> @@ -1654,6 +1666,7 @@ export function ExistingThreadSettingsRouteScreen({ updateModelSelection({ ...modelSelection, options }); }} runtimeMode={threadDraftSettings.runtimeMode ?? selectedThread.runtimeMode} + runtimeReadOnly={jarvisRuntimeIsReadOnly(selectedThread.source, structure?.projection.thread)} onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })} onClose={() => navigation.goBack()} /> diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 62964df445b37..bb2356fee0bb6 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2643,6 +2643,14 @@ "9468ea8c5e569821": "Dieses Gerät darf die Versionskontrolle in dieser Umgebung nicht ändern.", "3333d6830127e57f": "Verbinde dich erneut, um Änderungen vorzunehmen.", "92d0d4eab2596772": "Der Tracker hat es abgelehnt.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} ausstehend", + "6b1fe6f6e7358046": "Ich konnte nicht bestätigen, dass der heutige Thread geöffnet wurde.", + "971945028a5b334a": "Heutigen Thread öffnen", + "519f924d2d791e90": "Jarvis muss aktualisiert werden, bevor RuCode es verwenden kann.", + "6a67a7d36c43df57": "Jarvis ist nicht dort installiert, wo diese Umgebung es erwartet.", + "fa493aba5a3ccd76": "Wiederholen", + "1a8c505c6cba9504": "Ich kann diese Umgebung gerade nicht erreichen.", "ca958433a5eefdb2": "Neuer Thread in…", "b2de061402602d22": "Umgebungen verwalten", "09be015b51805a59": "Nutzung", @@ -5066,6 +5074,7 @@ "ed063bb30064ac7e": "Richte diesen Anbieter im Web oder auf dem Desktop ein oder wähle ein anderes Modell.", "f8cfb0a4af931a49": "Favoriten", "440285ac659c7832": "Laufzeit", + "45198a79fde0bc9f": "Lesen und Vorschläge machen", "a83559c38e1cd470": "Katalog", "16839051320ad525": "Ausgeblendete Modelle verwalten", "254dc4b4151094ef": "Modelle konnten nicht aktualisiert werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 25952cefce6f8..ba6ac416841ea 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2643,6 +2643,14 @@ "9468ea8c5e569821": "This device isn't allowed to change source control on this environment.", "3333d6830127e57f": "Reconnect to make changes.", "92d0d4eab2596772": "The tracker refused it.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} waiting", + "6b1fe6f6e7358046": "I couldn't confirm that today's thread opened.", + "971945028a5b334a": "Open today's thread", + "519f924d2d791e90": "Jarvis needs updating before RuCode can use it.", + "6a67a7d36c43df57": "Jarvis isn't installed where this environment expects it.", + "fa493aba5a3ccd76": "Retry", + "1a8c505c6cba9504": "I can't reach this environment right now.", "ca958433a5eefdb2": "New thread in…", "b2de061402602d22": "Manage environments", "09be015b51805a59": "Usage", @@ -5068,6 +5076,7 @@ "ed063bb30064ac7e": "Set up this provider on web or desktop, or select another model.", "f8cfb0a4af931a49": "Favorites", "440285ac659c7832": "Runtime", + "45198a79fde0bc9f": "Read and propose", "a83559c38e1cd470": "Catalog", "16839051320ad525": "Manage hidden models", "254dc4b4151094ef": "Could not refresh models", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 0c01a53f8e103..ee4cc1c6d76f4 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2639,6 +2639,14 @@ "9468ea8c5e569821": "Este dispositivo no tiene permiso para cambiar el control de versiones en este entorno.", "3333d6830127e57f": "Vuelve a conectarte para hacer cambios.", "92d0d4eab2596772": "El gestor de issues lo rechazó.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} en espera", + "6b1fe6f6e7358046": "No pude confirmar que se abriera el hilo de hoy.", + "971945028a5b334a": "Abrir el hilo de hoy", + "519f924d2d791e90": "Hay que actualizar Jarvis para que RuCode pueda usarlo.", + "6a67a7d36c43df57": "Jarvis no está instalado donde este entorno espera encontrarlo.", + "fa493aba5a3ccd76": "Reintentar", + "1a8c505c6cba9504": "Ahora mismo no puedo conectar con este entorno.", "ca958433a5eefdb2": "Nuevo hilo en…", "b2de061402602d22": "Gestionar entornos", "09be015b51805a59": "Uso", @@ -5059,6 +5067,7 @@ "ed063bb30064ac7e": "Configura este proveedor en la web o el escritorio, o selecciona otro modelo.", "f8cfb0a4af931a49": "Favoritos", "440285ac659c7832": "Modo de ejecución", + "45198a79fde0bc9f": "Leer y proponer", "a83559c38e1cd470": "Catálogo", "16839051320ad525": "Gestionar modelos ocultos", "254dc4b4151094ef": "No se pudieron actualizar los modelos", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 749fed1e4b9e7..9ddb6a56ca3cf 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2639,6 +2639,14 @@ "9468ea8c5e569821": "Cet appareil n’est pas autorisé à modifier la gestion de versions dans cet environnement.", "3333d6830127e57f": "Reconnectez-vous pour apporter des modifications.", "92d0d4eab2596772": "Le gestionnaire de tickets l’a refusé.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} en attente", + "6b1fe6f6e7358046": "Je n’ai pas pu confirmer l’ouverture du fil du jour.", + "971945028a5b334a": "Ouvrir le fil du jour", + "519f924d2d791e90": "Jarvis doit être mis à jour pour que RuCode puisse l’utiliser.", + "6a67a7d36c43df57": "Jarvis n’est pas installé à l’emplacement prévu par cet environnement.", + "fa493aba5a3ccd76": "Réessayer", + "1a8c505c6cba9504": "Je ne peux pas joindre cet environnement pour le moment.", "ca958433a5eefdb2": "Nouveau fil dans…", "b2de061402602d22": "Gérer les environnements", "09be015b51805a59": "Utilisation", @@ -5060,6 +5068,7 @@ "ed063bb30064ac7e": "Configurez ce fournisseur sur le web ou le bureau, ou sélectionnez un autre modèle.", "f8cfb0a4af931a49": "Favoris", "440285ac659c7832": "Exécution", + "45198a79fde0bc9f": "Lire et proposer", "a83559c38e1cd470": "Catalogue", "16839051320ad525": "Gérer les modèles masqués", "254dc4b4151094ef": "Impossible d’actualiser les modèles", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 5807884de4c6f..0b913f8c099ef 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2636,6 +2636,14 @@ "9468ea8c5e569821": "このデバイスには、この環境のソース管理を変更する権限がありません。", "3333d6830127e57f": "変更するには再接続してください。", "92d0d4eab2596772": "トラッカーが拒否しました。", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count}件が判断待ち", + "6b1fe6f6e7358046": "今日のスレッドが開いたか確認できませんでした。", + "971945028a5b334a": "今日のスレッドを開く", + "519f924d2d791e90": "RuCode で使うには Jarvis の更新が必要です。", + "6a67a7d36c43df57": "この環境が参照する場所に Jarvis がインストールされていません。", + "fa493aba5a3ccd76": "再試行", + "1a8c505c6cba9504": "今はこの環境に接続できません。", "ca958433a5eefdb2": "新しいスレッドの場所…", "b2de061402602d22": "環境を管理", "09be015b51805a59": "使用量", @@ -5039,6 +5047,7 @@ "ed063bb30064ac7e": "Web またはデスクトップでこのプロバイダーをセットアップするか、別のモデルを選択してください。", "f8cfb0a4af931a49": "お気に入り", "440285ac659c7832": "ランタイム", + "45198a79fde0bc9f": "読み取りと提案", "a83559c38e1cd470": "カタログ", "16839051320ad525": "非表示のモデルを管理", "254dc4b4151094ef": "モデルを更新できませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e89b367e5d499..91a6058871009 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2640,6 +2640,14 @@ "9468ea8c5e569821": "이 기기는 이 환경에서 소스 제어를 변경할 수 없습니다.", "3333d6830127e57f": "변경하려면 다시 연결하세요.", "92d0d4eab2596772": "트래커가 거부했습니다.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count}개 대기 중", + "6b1fe6f6e7358046": "오늘의 스레드가 열렸는지 확인하지 못했습니다.", + "971945028a5b334a": "오늘의 스레드 열기", + "519f924d2d791e90": "RuCode에서 사용하려면 Jarvis를 업데이트해야 합니다.", + "6a67a7d36c43df57": "이 환경에서 찾는 위치에 Jarvis가 설치되어 있지 않습니다.", + "fa493aba5a3ccd76": "다시 시도", + "1a8c505c6cba9504": "지금은 이 환경에 연결할 수 없습니다.", "ca958433a5eefdb2": "새 스레드 위치…", "b2de061402602d22": "환경 관리", "09be015b51805a59": "사용량", @@ -5044,6 +5052,7 @@ "ed063bb30064ac7e": "웹이나 데스크톱에서 이 제공자를 설정하거나 다른 모델을 선택하세요.", "f8cfb0a4af931a49": "즐겨찾기", "440285ac659c7832": "런타임", + "45198a79fde0bc9f": "읽고 제안하기", "a83559c38e1cd470": "카탈로그", "16839051320ad525": "숨긴 모델 관리", "254dc4b4151094ef": "모델을 새로 고칠 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pl.json b/apps/mobile/src/i18n/translations/pl.json index 4ada03b0c4c70..0952ead67320e 100644 --- a/apps/mobile/src/i18n/translations/pl.json +++ b/apps/mobile/src/i18n/translations/pl.json @@ -2643,6 +2643,14 @@ "9468ea8c5e569821": "To urządzenie nie może zmieniać kontroli wersji na tym środowisku.", "3333d6830127e57f": "Połącz ponownie, aby wprowadzić zmiany.", "92d0d4eab2596772": "Tracker to odrzucił.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} do rozpatrzenia", + "6b1fe6f6e7358046": "Nie udało mi się potwierdzić, że dzisiejszy wątek został otwarty.", + "971945028a5b334a": "Otwórz dzisiejszy wątek", + "519f924d2d791e90": "Aby RuCode mógł używać Jarvisa, trzeba go zaktualizować.", + "6a67a7d36c43df57": "Jarvis nie jest zainstalowany tam, gdzie szuka go to środowisko.", + "fa493aba5a3ccd76": "Ponów", + "1a8c505c6cba9504": "Nie mogę teraz połączyć się z tym środowiskiem.", "ca958433a5eefdb2": "Nowy wątek w…", "b2de061402602d22": "Zarządzaj środowiskami", "09be015b51805a59": "Użycie", @@ -5068,6 +5076,7 @@ "ed063bb30064ac7e": "Skonfiguruj tego dostawcę na webie lub desktopie albo wybierz inny model.", "f8cfb0a4af931a49": "Ulubione", "440285ac659c7832": "Środowisko uruchomieniowe", + "45198a79fde0bc9f": "Odczyt i propozycje", "a83559c38e1cd470": "Katalog", "16839051320ad525": "Zarządzaj ukrytymi modelami", "254dc4b4151094ef": "Nie udało się odświeżyć modeli", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 9fe134dce0415..000e4c6933e6e 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2639,6 +2639,14 @@ "9468ea8c5e569821": "Este dispositivo não tem permissão para alterar o controle de versão neste ambiente.", "3333d6830127e57f": "Reconecte para fazer alterações.", "92d0d4eab2596772": "O rastreador recusou.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} em espera", + "6b1fe6f6e7358046": "Não consegui confirmar que a thread de hoje foi aberta.", + "971945028a5b334a": "Abrir a thread de hoje", + "519f924d2d791e90": "É preciso atualizar o Jarvis para que o RuCode possa usá-lo.", + "6a67a7d36c43df57": "O Jarvis não está instalado no local esperado por este ambiente.", + "fa493aba5a3ccd76": "Tentar novamente", + "1a8c505c6cba9504": "Não consigo me conectar a este ambiente agora.", "ca958433a5eefdb2": "Nova thread em…", "b2de061402602d22": "Gerenciar ambientes", "09be015b51805a59": "Uso", @@ -5060,6 +5068,7 @@ "ed063bb30064ac7e": "Configure este provedor pela web ou pelo desktop, ou selecione outro modelo.", "f8cfb0a4af931a49": "Favoritos", "440285ac659c7832": "Runtime", + "45198a79fde0bc9f": "Ler e propor", "a83559c38e1cd470": "Catálogo", "16839051320ad525": "Gerenciar modelos ocultos", "254dc4b4151094ef": "Não foi possível atualizar os modelos", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index fa8deb97f3163..3581f7d78e11b 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2643,6 +2643,14 @@ "9468ea8c5e569821": "Этому устройству не разрешено менять контроль версий в этом окружении.", "3333d6830127e57f": "Переподключитесь, чтобы вносить изменения.", "92d0d4eab2596772": "Трекер отклонил запрос.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} в ожидании", + "6b1fe6f6e7358046": "Не удалось подтвердить, что сегодняшний тред открылся.", + "971945028a5b334a": "Открыть тред на сегодня", + "519f924d2d791e90": "Чтобы RuCode мог использовать Jarvis, его нужно обновить.", + "6a67a7d36c43df57": "Jarvis не установлен там, где его ищет это окружение.", + "fa493aba5a3ccd76": "Повторить", + "1a8c505c6cba9504": "Сейчас не получается подключиться к этому окружению.", "ca958433a5eefdb2": "Новый тред в…", "b2de061402602d22": "Управление окружениями", "09be015b51805a59": "Использование", @@ -5090,6 +5098,7 @@ "ed063bb30064ac7e": "Настройте этого провайдера в веб- или десктопной версии либо выберите другую модель.", "f8cfb0a4af931a49": "Избранное", "440285ac659c7832": "Режим работы", + "45198a79fde0bc9f": "Чтение и предложения", "a83559c38e1cd470": "Каталог", "16839051320ad525": "Управление скрытыми моделями", "254dc4b4151094ef": "Не удалось обновить модели", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7bc82af670f23..0b1dec21f55ec 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2643,6 +2643,14 @@ "9468ea8c5e569821": "Den här enheten får inte ändra versionshantering i den här miljön.", "3333d6830127e57f": "Anslut igen för att göra ändringar.", "92d0d4eab2596772": "Ärendehanteraren nekade.", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} väntar", + "6b1fe6f6e7358046": "Jag kunde inte bekräfta att dagens tråd öppnades.", + "971945028a5b334a": "Öppna dagens tråd", + "519f924d2d791e90": "Jarvis behöver uppdateras innan RuCode kan använda det.", + "6a67a7d36c43df57": "Jarvis är inte installerat på den plats där miljön förväntar sig det.", + "fa493aba5a3ccd76": "Försök igen", + "1a8c505c6cba9504": "Jag kan inte nå den här miljön just nu.", "ca958433a5eefdb2": "Ny tråd i…", "b2de061402602d22": "Hantera miljöer", "09be015b51805a59": "Användning", @@ -5066,6 +5074,7 @@ "ed063bb30064ac7e": "Konfigurera leverantören på webben eller skrivbordet, eller välj en annan modell.", "f8cfb0a4af931a49": "Favoriter", "440285ac659c7832": "Körläge", + "45198a79fde0bc9f": "Läsa och föreslå", "a83559c38e1cd470": "Katalog", "16839051320ad525": "Hantera dolda modeller", "254dc4b4151094ef": "Kunde inte uppdatera modeller", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index da76c613115aa..d32c3f0f5ca23 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2640,6 +2640,14 @@ "9468ea8c5e569821": "此设备无权更改此环境上的版本控制。", "3333d6830127e57f": "重新连接以进行更改。", "92d0d4eab2596772": "跟踪器拒绝了操作。", + "43578ef6d5252f56": "Jarvis · {day}", + "53b6a1bb66a65417": "{count} 项待处理", + "6b1fe6f6e7358046": "我无法确认今天的会话是否已打开。", + "971945028a5b334a": "打开今天的会话", + "519f924d2d791e90": "Jarvis 需要更新后才能供 RuCode 使用。", + "6a67a7d36c43df57": "Jarvis 未安装在此环境预期的位置。", + "fa493aba5a3ccd76": "重试", + "1a8c505c6cba9504": "我现在无法连接到此环境。", "ca958433a5eefdb2": "新建会话于…", "b2de061402602d22": "管理环境", "09be015b51805a59": "用量", @@ -5048,6 +5056,7 @@ "ed063bb30064ac7e": "请在网页端或桌面端设置此提供方,或选择其他模型。", "f8cfb0a4af931a49": "收藏", "440285ac659c7832": "运行环境", + "45198a79fde0bc9f": "读取并提出建议", "a83559c38e1cd470": "目录", "16839051320ad525": "管理隐藏的模型", "254dc4b4151094ef": "无法刷新模型", diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 3fe06b078a595..97f06f2c21c49 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -71,6 +71,7 @@ const reactTests = [ "src/features/connection/useRetryEnvironment.test.tsx", "src/features/connection/ConnectionsNewRouteScreen.test.tsx", "src/features/connection/LinkedEnvironmentsSection.test.tsx", + "src/features/jarvis/JarvisHomeEntry.test.tsx", "src/features/devices/device-stream.browser.test.ts", "src/features/keyboard/keyboardControllerState.test.tsx", "src/features/voice-input/useVoiceInputController.test.tsx", diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index e87a39c01c470..7e5a9863600ac 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -14,6 +14,7 @@ import { IssueTrackerKind, type LocalApi, ProjectId, + type PluginThreadCards, ProviderInstanceId, ThreadId, type ScopedThreadRef, @@ -48,6 +49,7 @@ import { useDispatchDecisionThreadKeys, useThreadCliSession, } from "../pluginCards/live/liveAtoms"; +import { usePluginThreadCards } from "../pluginCards/core/usePluginCards"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -90,6 +92,7 @@ vi.mock("./sidebar/SidebarChrome", () => ({ ), })); vi.mock("../pluginCards/live/liveAtoms", { spy: true }); +vi.mock("../pluginCards/core/usePluginCards", { spy: true }); // The live plugin state comes over a connection these tests never open. vi.mocked(useDispatchDecisionThreadKeys).mockReturnValue(new Set()); vi.mocked(useDispatchDecisionCounts).mockReturnValue(new Map()); @@ -1363,3 +1366,197 @@ describe("sidebar thread card layout", () => { } }); }); + +describe("sidebar Jarvis days", () => { + const listProject = project("active"); + const environmentId = listProject.environmentId; + const PINNED_AT = "2026-12-01T06:00:00.000Z"; + const jarvisShell = ( + id: string, + tags: string[], + overrides: Parameters[0] = {}, + ) => { + const base = makeThreadFixture({ + environmentId, + projectId: listProject.id, + id: ThreadId.make(id), + title: id, + ...overrides, + }); + return { ...base, source: { ...base.source, tags } }; + }; + const today = jarvisShell("jarvis-today", ["jarvis", "jarvis:2026-12-01"], { + title: "Jarvis · 2026-12-01", + pinnedAt: PINNED_AT, + }); + const yesterday = jarvisShell("jarvis-yesterday", ["jarvis", "jarvis:2026-11-30"], { + title: "Jarvis · 2026-11-30", + }); + const plain = makeThreadFixture({ + environmentId, + projectId: listProject.id, + id: ThreadId.make("plain"), + title: "Checkout retries", + }); + const keyOf = (thread: EnvironmentThreadShell) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const AT = "2026-12-01T08:00:00.000Z"; + const proposal = (id: string, state: "proposed" | "succeeded") => ({ + id: `jarvis.proposal:${id}`, + threadId: today.id, + kind: "jarvis.proposal", + placement: { type: "time", at: AT }, + updatedAt: AT, + actions: + state === "proposed" + ? [ + { id: "confirm:hash", label: "Confirm", type: "command" }, + { id: "cancel:hash", label: "Cancel", type: "command" }, + ] + : [], + data: { + card: { + id, + threadId: today.id, + kind: "reply", + title: `Card ${id}`, + source: "group/app", + ask: "Reply?", + context: null, + options: [], + effectText: "Reply", + effectHash: "hash", + state, + reason: null, + proposedAt: AT, + decidedAt: null, + settledAt: null, + expiresAt: null, + outcome: null, + }, + }, + }); + + function setup(threads: EnvironmentThreadShell[], routeThread: EnvironmentThreadShell | null) { + const stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: false }); + const routeRef = + routeThread === null ? null : scopeThreadRef(routeThread.environmentId, routeThread.id); + vi.mocked(useProjects).mockReturnValue([listProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue( + routeRef === null ? null : { kind: "server", threadRef: routeRef }, + ); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { environmentId, projectId: listProject.id }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: routeRef, + }); + vi.mocked(useServerConfigs).mockReturnValue( + new Map([ + [ + environmentId, + { + scratchWorkspaceRoot: null, + shellThreadFamilies: false, + } as unknown as EnvironmentServerConfig, + ], + ]), + ); + stack.defer(() => vi.mocked(useServerConfigs).mockRestore()); + const cardRefs: Array = []; + vi.mocked(usePluginThreadCards).mockImplementation((threadRef) => { + cardRefs.push(threadRef); + return threadRef?.threadId === today.id + ? ({ + threadId: today.id, + cards: [ + proposal("a", "proposed"), + proposal("b", "succeeded"), + proposal("c", "proposed"), + ], + } as unknown as PluginThreadCards) + : null; + }); + stack.defer(() => vi.mocked(usePluginThreadCards).mockRestore()); + return { stack, cardRefs }; + } + + const ui = () => ( + + + + ); + const row = (container: HTMLElement, thread: EnvironmentThreadShell) => + container.querySelector(`[data-sidebar-row="${keyOf(thread)}"]`); + async function setSettledShelf(container: HTMLElement, expanded: boolean) { + const shelf = container.querySelector('[data-sidebar-row="shelf:settled"]')!; + if ((shelf.getAttribute("aria-expanded") === "true") !== expanded) { + await act(() => shelf.click()); + } + } + + it("pins today's row with its waiting count and puts earlier days on the collapsed Settled shelf", async () => { + const { stack, cardRefs } = setup([today, yesterday, plain], null); + using _stack = stack; + await using screen = await render(ui()); + await vi.waitFor(() => expect(row(screen.container, today)).not.toBeNull()); + await setSettledShelf(screen.container, false); + + const todayRow = row(screen.container, today)!; + expect(todayRow.getAttribute("aria-label")).toBe( + "Jarvis · Tue Dec 1, 2 waiting on you, active", + ); + expect(todayRow.textContent).toContain("Jarvis · Tue Dec 1"); + expect(todayRow.querySelector("[aria-hidden='true'].tabular-nums")?.textContent).toBe("2"); + expect(todayRow.getAttribute("data-sidebar-parent")).toBeNull(); + expect(row(screen.container, plain)?.getAttribute("data-sidebar-parent")).toBeNull(); + expect(row(screen.container, yesterday)).toBeNull(); + + await setSettledShelf(screen.container, true); + await vi.waitFor(() => expect(row(screen.container, yesterday)).not.toBeNull()); + const yesterdayRow = row(screen.container, yesterday)!; + expect(yesterdayRow.getAttribute("data-sidebar-parent")).toBe("shelf:settled"); + expect(yesterdayRow.textContent).toContain("Jarvis · Mon Nov 30"); + expect(yesterdayRow.getAttribute("aria-label")).not.toContain("waiting on you"); + expect( + cardRefs.every((threadRef) => threadRef === null || threadRef.threadId === today.id), + ).toBe(true); + await setSettledShelf(screen.container, false); + }); + + it("still draws the open earlier Jarvis thread under the collapsed Settled shelf", async () => { + const { stack } = setup([today, yesterday, plain], yesterday); + using _stack = stack; + await using screen = await render(ui()); + await vi.waitFor(() => expect(row(screen.container, today)).not.toBeNull()); + await setSettledShelf(screen.container, false); + + await vi.waitFor(() => + expect(row(screen.container, yesterday)?.getAttribute("data-sidebar-parent")).toBe( + "shelf:settled", + ), + ); + }); + + it("leaves a Jarvis thread with a malformed day tag in Active under its stored title", async () => { + const malformed = jarvisShell("jarvis-malformed", ["jarvis", "jarvis:2026-13-01"], { + title: "Jarvis · 2026-13-01", + }); + const { stack } = setup([today, malformed], null); + using _stack = stack; + await using screen = await render(ui()); + await vi.waitFor(() => expect(row(screen.container, malformed)).not.toBeNull()); + await setSettledShelf(screen.container, false); + + const malformedRow = row(screen.container, malformed)!; + expect(malformedRow.getAttribute("data-sidebar-parent")).toBeNull(); + expect(malformedRow.getAttribute("aria-label")).toBe("Jarvis · 2026-13-01, active"); + }); +}); diff --git a/apps/web/src/components/Sidebar.drag.browser.test.tsx b/apps/web/src/components/Sidebar.drag.browser.test.tsx index 68bf17b43f160..b85d68bebb277 100644 --- a/apps/web/src/components/Sidebar.drag.browser.test.tsx +++ b/apps/web/src/components/Sidebar.drag.browser.test.tsx @@ -1,4 +1,7 @@ import { createMemoryHistory } from "@tanstack/react-router"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { ThreadId } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import type * as Context from "effect/Context"; import { expect, it, vi } from "vite-plus/test"; @@ -9,7 +12,9 @@ import { AppRoot } from "~/AppRoot"; import "~/components/ChatView"; import { __setClientSettingsForTests } from "~/hooks/useSettings"; import { getRouter } from "~/router"; +import { useQuietThreadShells } from "~/state/entities"; import { + dispatchedCommands, ENVIRONMENT_ID, installFakeEnvironment, threadWithHistory, @@ -34,6 +39,11 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ trackRpcRequestSent: () => {}, })); +vi.mock(import("~/state/entities"), async (original) => { + const actual = await original(); + return { ...actual, useQuietThreadShells: vi.fn(actual.useQuietThreadShells) }; +}); + it("shows the titled preview inside and outside search results from a collapsed folder", async () => { await page.viewport(1400, 900); const [first, second] = [threadWithHistory("visible", 1), threadWithHistory("search-target", 1)]; @@ -141,3 +151,96 @@ it("keeps focus in the search box when a click picks a search result", async () // A focused result would take focus from the search box, and its recovery scrolls the list. await expect.element(search).toHaveFocus(); }); + +/** The fake environment writes no thread tags, so this adds them to the sidebar's shells. */ +function tagThreadShells(tagsById: ReadonlyMap>): Disposable { + const real = vi.mocked(useQuietThreadShells).getMockImplementation()!; + const tagged = new WeakMap< + ReadonlyArray, + ReadonlyArray + >(); + vi.mocked(useQuietThreadShells).mockImplementation(() => { + const shells = real(); + const cached = tagged.get(shells); + if (cached !== undefined) return cached; + const next = shells.map((shell) => { + const tags = tagsById.get(shell.id); + return tags === undefined ? shell : { ...shell, source: { ...shell.source, tags } }; + }); + tagged.set(shells, next); + return next; + }); + return { [Symbol.dispose]: () => vi.mocked(useQuietThreadShells).mockImplementation(real) }; +} + +it("un-settles an earlier Jarvis day once when it is dragged off the Settled shelf", async () => { + await page.viewport(1400, 900); + // The app keeps this file's first connection and its shells, so these reuse that test's threads. + const [today, yesterday] = [ + threadWithHistory("visible", 1), + threadWithHistory("search-target", 1), + ]; + using _environment = installFakeEnvironment([today, yesterday]); + using _tags = tagThreadShells( + new Map([ + [today.id, ["jarvis", "jarvis:2026-12-01"]], + [yesterday.id, ["jarvis", "jarvis:2026-11-30"]], + ]), + ); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + boringSidebarEnabled: false, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${today.id}`] }), + ); + await router.load(); + await using _app = await render(, { router: false }); + const rowOf = (threadId: ThreadId) => + document.querySelector( + `[data-sidebar-row="${scopedThreadKey(scopeThreadRef(ENVIRONMENT_ID, threadId))}"]`, + ); + const shelf = page.getByTestId("sidebar-settled-shelf-toggle"); + await expect.element(shelf).toHaveTextContent("Settled1"); + // The shift guard drops presses on rows that moved without the user's own input; a key is one. + if (shelf.element().getAttribute("aria-expanded") !== "true") { + (shelf.element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); + } + await vi.waitFor(() => + expect(rowOf(yesterday.id)?.getAttribute("data-sidebar-parent")).toBe("shelf:settled"), + ); + expect(rowOf(today.id)?.getAttribute("data-sidebar-parent")).toBeNull(); + + const from = rowOf(yesterday.id)!.getBoundingClientRect(); + const to = rowOf(today.id)!.getBoundingClientRect(); + const pointer = (type: string, x: number, y: number) => + new PointerEvent(type, { + bubbles: true, + cancelable: true, + pointerId: 1, + isPrimary: true, + button: 0, + buttons: type === "pointerup" ? 0 : 1, + clientX: x, + clientY: y, + }); + const [startX, startY] = [from.x + 40, from.y + from.height / 2]; + const [endX, endY] = [to.x + 40, to.y + to.height / 2]; + await act(() => rowOf(yesterday.id)!.dispatchEvent(pointer("pointerdown", startX, startY))); + for (const step of [0.1, 0.4, 0.7, 1]) { + await act(() => + document.dispatchEvent(pointer("pointermove", startX, startY + (endY - startY) * step)), + ); + } + await act(() => document.dispatchEvent(pointer("pointerup", endX, endY))); + + await vi.waitFor(() => + expect(dispatchedCommands().filter((command) => command.type === "thread.unsettle")).toEqual([ + expect.objectContaining({ threadId: yesterday.id }), + ]), + ); + expect(dispatchedCommands().filter((command) => command.type === "thread.settle")).toEqual([]); + expect(rowOf(yesterday.id)?.getAttribute("data-sidebar-parent")).toBeNull(); +}); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 6ba0e0e98f399..a4f554ec31fb7 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -305,6 +305,7 @@ import { SidebarSectionHeader, SidebarSectionPlaceholder, } from "./sidebar/SidebarListMarkers"; +import { earlierJarvisThreadKeys } from "./sidebar/jarvisSidebar.logic"; function sameSidebarProviderEntries( left: ReadonlyMap, @@ -761,6 +762,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { : active; const snoozed: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = []; + // From every thread, so a project filter that hides today's row cannot make yesterday's the newest. + const earlierJarvis = earlierJarvisThreadKeys(threads); const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({ threads: visible, serverConfigs, @@ -789,7 +792,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { } else { const section = resolveSidebarThreadSection({ snoozed: configLoaded && effectiveSnoozed(thread, { now: preciseNow }), - settled: configLoaded && thread.settledOverride === "settled", + settled: + configLoaded && (thread.settledOverride === "settled" || earlierJarvis.has(threadKey)), pinned: thread.pinnedAt != null, }); (section === "snoozed" @@ -837,6 +841,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { settledThreads: sortSettledThreads(settled), visibleThreads: visible, snoozeNow: preciseNow, + earlierJarvisThreadKeys: earlierJarvis, }; } @@ -1496,6 +1501,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve decisionRowKeys, uncarriedDecisionCount, waitingThreadKeys, + earlierJarvisThreadKeys: earlierJarvisSettledKeys, } = useSidebarThreads({ projectScopeKey, scopedProjectKeys, @@ -2269,7 +2275,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve activeKey: draggedThreadKey, activeSection: draggedFromSection, activePinned: source.pinnedAt != null, - activeSettled: source.settledOverride === "settled", + activeSettled: + source.settledOverride === "settled" || + earlierJarvisSettledKeys.has(draggedThreadKey), supportsSettlement: serverConfigs.has(source.environmentId), target, pinnedOrder: pinnedKeys, @@ -2303,7 +2311,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve activeKey, activeSection, activePinned: activeThread.pinnedAt != null, - activeSettled: activeThread.settledOverride === "settled", + // An earlier Jarvis day sits on the shelf unsettled; without this the drop sends no + // unsettle and the row snaps back. + activeSettled: + activeThread.settledOverride === "settled" || earlierJarvisSettledKeys.has(activeKey), supportsSettlement: serverConfigs.has(activeThread.environmentId), target, pinnedOrder: pinnedKeys, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index ed4b1b49a073d..4485ef20476d9 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -146,6 +146,7 @@ import { ComposerBanner } from "./ComposerBanner"; import { ComposerSurface } from "./ComposerSurface"; import { CollapsedComposerPromptPreview } from "./CollapsedComposerPromptPreview"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack"; +import { useJarvisTellBannerItem } from "../jarvis/jarvisTellBanner"; import { attachmentsToReleaseOnUploadCapabilityLoss, composerOtherFilesForPresentation, @@ -3115,12 +3116,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, ] : []; + const jarvisTellBanner = useJarvisTellBannerItem(composerDraftTarget); + const composerBannerItems = [...props.bannerItems, ...replyBannerItems]; + if (jarvisTellBanner) composerBannerItems.push(jarvisTellBanner); const bannerItems: readonly ComposerBannerStackItem[] = runtimeModeCeilingDenial === undefined || activePendingProgress - ? [...props.bannerItems, ...replyBannerItems] + ? composerBannerItems : [ - ...props.bannerItems, - ...replyBannerItems, + ...composerBannerItems, { id: "managed-runtime-mode", variant: "warning", diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index 0688cdfe2b2ad..f521421cc7cff 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -12,6 +12,7 @@ import { type RuntimeModeOption, } from "./ComposerFooterControls"; import { + isJarvisThread, type EnvironmentId, type ModelSelection, type ProviderDriverKind, @@ -31,6 +32,7 @@ import { } from "./ComposerModelEffort"; import type { useComposerProviderModel } from "./useComposerProviderModel"; import { resolveComposerControlsOwnership } from "./composerControlsOwnership"; +import { useThreadShell } from "../../state/entities"; /** * The composer footer controls: the model picker (which also holds effort, speed and @@ -132,6 +134,7 @@ export function ComposerControlsBar(props: { modelPickerIconClassName, getModelDisabledReason, } = props; + const isJarvis = isJarvisThread({ tags: useThreadShell(routeThreadRef)?.source.tags }); const accessMatchesDefault = compatibleRuntimeMode === defaultRuntimeMode; const { accessDisplay, @@ -141,7 +144,7 @@ export function ComposerControlsBar(props: { overflowShowsPermissions, pickerOwnsModeShortcut, } = resolveComposerControlsOwnership({ - matchesDefault: accessMatchesDefault || props.permissionsShownInStrip, + matchesDefault: isJarvis || accessMatchesDefault || props.permissionsShownInStrip, collapsed: composerControlsCollapsed, measuredHiddenBlockCount, }); @@ -165,24 +168,19 @@ export function ComposerControlsBar(props: { onPromptEdit, }); const effort = describeComposerEffort(traitsInput, props.effortDisplay, controlSize, m); - const restingBlockDefs = showModeBlock - ? [ - { - id: "mode", - content: ( -