feat: add bookmark logic

This commit is contained in:
Patrick Erichsen 2025-03-21 11:04:04 -07:00
parent 1d1f705f7d
commit d3f4aeb4c6
16 changed files with 165 additions and 126 deletions

View file

@ -529,7 +529,7 @@ class VsCodeIde implements IDE {
const tabArray = vscode.window.tabGroups.all[0].tabs;
return tabArray
.filter((t) => t.isPinned)
.filter((t) => t.isBookmarked)
.map((t) => (t.input as vscode.TabInputText).uri.toString());
}

View file

@ -1,33 +1,63 @@
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import { BookmarkIcon, ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import { BookmarkIcon as BookmarkIconSolid } from "@heroicons/react/24/solid";
import { SlashCommandDescription } from "core";
import { defaultBorderRadius, vscInputBackground } from "..";
import { useState } from "react";
import { defaultBorderRadius, GhostButton, vscInputBackground } from "..";
interface ConversationStarterCardProps {
command: SlashCommandDescription;
onClick: (command: SlashCommandDescription) => void;
onBookmark: (command: SlashCommandDescription) => void;
isBookmarked: boolean;
}
export function ConversationStarterCard({
command,
onClick,
onBookmark,
isBookmarked = false,
}: ConversationStarterCardProps) {
const [isHovered, setIsHovered] = useState(false);
return (
<div
onClick={() => onClick(command)}
className="mb-2 w-full shadow-md hover:cursor-pointer hover:brightness-110"
className="mb-2 w-full shadow-md hover:brightness-110"
style={{
borderRadius: defaultBorderRadius,
backgroundColor: vscInputBackground,
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="flex items-center px-3 py-2">
<div className="flex items-center px-3 py-1.5">
<div className="mr-3 flex-shrink-0">
<ChatBubbleLeftIcon className="text-lightgray h-5 w-5" />
</div>
<div className="flex flex-col">
<div
onClick={() => onClick(command)}
className="flex flex-1 flex-col hover:cursor-pointer"
>
<div className="font-medium">{command.name}</div>
<div className="text-lightgray text-sm">{command.description}</div>
</div>
<div className="flex items-center">
<GhostButton
onClick={(e) => {
e.stopPropagation();
onBookmark(command);
}}
aria-label={
isBookmarked ? "Remove bookmarked prompt" : "Bookmark prompt"
}
className={isHovered || isBookmarked ? "opacity-100" : "opacity-0"}
>
{isBookmarked ? (
<BookmarkIconSolid className="h-4 w-4" />
) : (
<BookmarkIcon className="h-4 w-4" />
)}
</GhostButton>
</div>
</div>
</div>
);

View file

@ -10,19 +10,13 @@ const NUM_CARDS_TO_RENDER_COLLAPSED = 3;
export function ConversationStarterCards() {
const dispatch = useAppDispatch();
const [isExpanded, setIsExpanded] = useState(false);
const [bookmarkedCommands, setBookmarkedCommands] = useState<string[]>([]);
const slashCommands =
useAppSelector((state) => state.config.config.slashCommands) ?? [];
const filteredSlashCommands = slashCommands?.filter(isDeprecatedCommandName);
const numFilteredSlashCommands = filteredSlashCommands.length;
const displayedCommands = isExpanded
? filteredSlashCommands
: filteredSlashCommands.slice(0, NUM_CARDS_TO_RENDER_COLLAPSED);
const hasMoreCommands =
numFilteredSlashCommands > NUM_CARDS_TO_RENDER_COLLAPSED;
function onClick(command: SlashCommandDescription) {
if (command.prompt) {
dispatch(
@ -31,8 +25,14 @@ export function ConversationStarterCards() {
}
}
function handleToggleExpand() {
setIsExpanded(!isExpanded);
function handleBookmarkCommand(command: SlashCommandDescription) {
setBookmarkedCommands((prev) => {
if (prev.includes(command.name)) {
return prev.filter((name) => name !== command.name);
} else {
return [...prev, command.name];
}
});
}
if (!filteredSlashCommands || filteredSlashCommands.length === 0) {
@ -40,29 +40,18 @@ export function ConversationStarterCards() {
}
return (
<div className="flex flex-col items-center">
<h4 className="mb-2 w-full max-w-md self-start">Prompts</h4>
<div className="w-full max-w-md">
{displayedCommands.map((command, i) => (
<div className="flex w-full max-w-full flex-col lg:grid lg:grid-cols-3 lg:gap-4">
{filteredSlashCommands
.slice(0, NUM_CARDS_TO_RENDER_COLLAPSED)
.map((command, i) => (
<ConversationStarterCard
key={command.name + i}
command={command}
onClick={onClick}
onBookmark={handleBookmarkCommand}
isBookmarked={bookmarkedCommands.includes(command.name)}
/>
))}
</div>
{hasMoreCommands && (
<p
onClick={handleToggleExpand}
className="text-lightgray cursor-pointer self-start text-xs hover:underline"
>
{isExpanded
? "Show less"
: `Show ${numFilteredSlashCommands - NUM_CARDS_TO_RENDER_COLLAPSED} more...`}
</p>
)}
</div>
);
}

View file

@ -1,5 +1,5 @@
import styled from "styled-components";
import { getFontSize, isJetBrains } from "../util";
import { getFontSize } from "../util";
export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
@ -151,7 +151,7 @@ export const SecondaryButton = styled.button`
`;
export const GhostButton = styled.button`
padding: 10px 12px;
padding: 6px 8px;
margin: 8px 0;
border-radius: ${defaultBorderRadius};

View file

@ -5,7 +5,7 @@ import { useContext, useEffect, useRef } from "react";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch } from "../../../redux/hooks";
import { cycleProfile } from "../../../redux/thunks/profileAndOrg";
import { cycleProfile } from "../../../redux/slices/profiles/thunks";
import { getFontSize, isMetaEquivalentKeyPressed } from "../../../util";
import PopoverTransition from "../../mainInput/InputToolbar/PopoverTransition";
import AssistantIcon from "./AssistantIcon";

View file

@ -6,7 +6,7 @@ import { lightGray } from "../..";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch } from "../../../redux/hooks";
import { selectProfileThunk } from "../../../redux/thunks/profileAndOrg";
import { selectProfileThunk } from "../../../redux/slices/profiles/thunks";
import { getFontSize, getMetaKeyLabel, isLocalProfile } from "../../../util";
import { ROUTES } from "../../../util/navigation";
import AssistantIcon from "./AssistantIcon";

View file

@ -14,11 +14,11 @@ import ConfirmationDialog from "../components/dialogs/ConfirmationDialog";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice";
import {
updateOrgsThunk,
updateProfilesThunk,
} from "../redux/thunks/profileAndOrg";
} from "../redux/slices/profiles/thunks";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice";
import { IdeMessengerContext } from "./IdeMessenger";
interface AuthContextType {
@ -47,9 +47,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
);
// Orgs
const orgs = useAppSelector((store) => store.session.organizations);
const orgs = useAppSelector((store) => store.profiles.organizations);
const selectedOrgId = useAppSelector(
(store) => store.session.selectedOrganizationId,
(store) => store.profiles.selectedOrganizationId,
);
const selectedOrganization = useMemo(() => {
if (!selectedOrgId) {
@ -59,9 +59,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
}, [orgs, selectedOrgId]);
// Profiles
const profiles = useAppSelector((store) => store.session.availableProfiles);
const profiles = useAppSelector((store) => store.profiles.availableProfiles);
const selectedProfile = useAppSelector(
(store) => store.session.selectedProfile,
(store) => store.profiles.selectedProfile,
);
const login: AuthContextType["login"] = (useOnboarding: boolean) => {

View file

@ -11,12 +11,12 @@ import {
} from "../redux/slices/configSlice";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import { updateDocsSuggestions } from "../redux/slices/miscSlice";
import { selectProfileThunk } from "../redux/slices/profiles/thunks";
import {
addContextItemsAtIndex,
setInactive,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { selectProfileThunk } from "../redux/thunks/profileAndOrg";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";

View file

@ -7,12 +7,12 @@ import {
import { useAuth } from "../../context/Auth";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectOrgThunk } from "../../redux/thunks/profileAndOrg";
import { selectOrgThunk } from "../../redux/slices/profiles/thunks";
export function ScopeSelect() {
const { organizations, selectedOrganization } = useAuth();
const selectedOrgId = useAppSelector(
(state) => state.session.selectedOrganizationId,
(state) => state.profiles.selectedOrganizationId,
);
const dispatch = useAppDispatch();

View file

@ -29,7 +29,7 @@ import {
setDefaultModel,
updateConfig,
} from "../../redux/slices/configSlice";
import { selectProfileThunk } from "../../redux/thunks/profileAndOrg";
import { selectProfileThunk } from "../../redux/slices/profiles/thunks";
import { getFontSize, isJetBrains } from "../../util";
import ModelRoleSelector from "./ModelRoleSelector";
import { ScopeSelect } from "./ScopeSelect";

View file

@ -22,7 +22,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
const selectedModel = useAppSelector(selectDefaultModel);
const hubEnabled = useAppSelector(selectUseHub);
const selectedProfile = useAppSelector(
(store) => store.session.selectedProfile,
(store) => store.profiles.selectedProfile,
);
const { session, refreshProfiles } = useAuth();

View file

@ -0,0 +1,2 @@
export * from "./slice";
export * from "./thunks";

View file

@ -0,0 +1,59 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ProfileDescription } from "core/config/ConfigHandler";
import { OrganizationDescription } from "core/config/ProfileLifecycleManager";
interface ProfilesState {
availableProfiles: ProfileDescription[] | null;
selectedProfile: ProfileDescription | null;
organizations: OrganizationDescription[];
selectedOrganizationId: string | null;
}
const initialState: ProfilesState = {
availableProfiles: null,
selectedProfile: null,
organizations: [],
selectedOrganizationId: null,
};
export const profilesSlice = createSlice({
name: "profiles",
initialState,
// Important: these reducers don't handle selected profile/organization fallback logic
// That is done in thunks
reducers: {
setSelectedProfile: (
state,
{ payload }: PayloadAction<ProfileDescription | null>,
) => {
state.selectedProfile = payload;
},
setAvailableProfiles: (
state,
{ payload }: PayloadAction<ProfileDescription[] | null>,
) => {
state.availableProfiles = payload;
},
setOrganizations: (
state,
{ payload }: PayloadAction<OrganizationDescription[]>,
) => {
state.organizations = payload;
},
setSelectedOrganizationId: (
state,
{ payload }: PayloadAction<string | null>,
) => {
state.selectedOrganizationId = payload;
},
},
});
export const {
setSelectedProfile,
setAvailableProfiles,
setOrganizations,
setSelectedOrganizationId,
} = profilesSlice.actions;
export const profilesReducer = profilesSlice.reducer;

View file

@ -1,13 +1,13 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ProfileDescription } from "core/config/ConfigHandler";
import { OrganizationDescription } from "core/config/ProfileLifecycleManager";
import { ThunkApiType } from "../../store";
import {
setAvailableProfiles,
setOrganizations,
setSelectedOrganizationId,
setSelectedProfile,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
} from "./slice";
export const selectProfileThunk = createAsyncThunk<
void,
@ -16,29 +16,29 @@ export const selectProfileThunk = createAsyncThunk<
>("profiles/select", async (id, { dispatch, extra, getState }) => {
const state = getState();
if (state.session.availableProfiles === null) {
if (state.profiles.availableProfiles === null) {
// Currently in loading state
return;
}
const initialId = state.session.selectedProfile?.id;
const initialId = state.profiles.selectedProfile?.id;
let newId = id;
// If no profiles, force clear
if (state.session.availableProfiles.length === 0) {
if (state.profiles.availableProfiles.length === 0) {
newId = null;
} else {
// If new id doesn't match an existing profile, clear it
if (newId) {
if (!state.session.availableProfiles.find((p) => p.id === newId)) {
if (!state.profiles.availableProfiles.find((p) => p.id === newId)) {
newId = null;
}
}
if (!newId) {
// At this point if null ID and there ARE profiles,
// Fallback to a profile, prioritizing the first in the list
newId = state.session.availableProfiles[0].id;
newId = state.profiles.availableProfiles[0].id;
}
}
@ -46,7 +46,7 @@ export const selectProfileThunk = createAsyncThunk<
if ((newId ?? null) !== (initialId ?? null)) {
dispatch(
setSelectedProfile(
state.session.availableProfiles.find((p) => p.id === newId) ?? null,
state.profiles.availableProfiles.find((p) => p.id === newId) ?? null,
),
);
extra.ideMessenger.post("didChangeSelectedProfile", {
@ -60,11 +60,11 @@ export const cycleProfile = createAsyncThunk<void, undefined, ThunkApiType>(
async (_, { dispatch, getState }) => {
const state = getState();
if (state.session.availableProfiles === null) {
if (state.profiles.availableProfiles === null) {
return;
}
const profileIds = state.session.availableProfiles.map(
const profileIds = state.profiles.availableProfiles.map(
(profile) => profile.id,
);
// In case of no profiles just does nothing
@ -72,8 +72,8 @@ export const cycleProfile = createAsyncThunk<void, undefined, ThunkApiType>(
return;
}
let nextId = profileIds[0];
if (state.session.selectedProfile) {
const curIndex = profileIds.indexOf(state.session.selectedProfile?.id);
if (state.profiles.selectedProfile) {
const curIndex = profileIds.indexOf(state.profiles.selectedProfile?.id);
const nextIndex = (curIndex + 1) % profileIds.length;
nextId = profileIds[nextIndex];
}
@ -100,15 +100,15 @@ export const selectOrgThunk = createAsyncThunk<
ThunkApiType
>("session/selectOrg", async (id, { dispatch, extra, getState }) => {
const state = getState();
const initialId = state.session.selectedOrganizationId;
const initialId = state.profiles.selectedOrganizationId;
let newId = id;
// If no orgs, force clear
if (state.session.organizations.length === 0) {
if (state.profiles.organizations.length === 0) {
newId = null;
} else if (newId) {
// If new id doesn't match an existing org, clear it
if (!state.session.organizations.find((o) => o.id === newId)) {
if (!state.profiles.organizations.find((o) => o.id === newId)) {
newId = null;
}
}
@ -133,5 +133,5 @@ export const updateOrgsThunk = createAsyncThunk<
dispatch(setOrganizations(orgs));
// This will trigger reselection if needed
dispatch(selectOrgThunk(state.session.selectedOrganizationId));
dispatch(selectOrgThunk(state.profiles.selectedOrganizationId));
});

View file

@ -21,8 +21,6 @@ import {
ToolCallDelta,
ToolCallState,
} from "core";
import { ProfileDescription } from "core/config/ConfigHandler";
import { OrganizationDescription } from "core/config/ProfileLifecycleManager";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { incrementalParseJson } from "core/util/incrementalParseJson";
import { renderChatMessage } from "core/util/messageContent";
@ -45,11 +43,6 @@ type SessionState = {
isStreaming: boolean;
title: string;
id: string;
/** null indicates loading state */
availableProfiles: ProfileDescription[] | null;
selectedProfile: ProfileDescription | null;
organizations: OrganizationDescription[];
selectedOrganizationId: string | null;
streamAborter: AbortController;
codeToEdit: CodeToEdit[];
curCheckpointIndex: number;
@ -88,10 +81,6 @@ const initialState: SessionState = {
isStreaming: false,
title: NEW_SESSION_TITLE,
id: uuidv4(),
selectedProfile: null,
availableProfiles: null,
organizations: [],
selectedOrganizationId: "",
curCheckpointIndex: 0,
streamAborter: new AbortController(),
codeToEdit: [],
@ -294,7 +283,6 @@ export const sessionSlice = createSlice({
state.streamAborter = new AbortController();
},
streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
if (state.history.length) {
function toolCallDeltaToState(
toolCallDelta: ToolCallDelta,
@ -332,7 +320,7 @@ export const sessionSlice = createSlice({
id: uuidv4(),
},
contextItems: [],
})
});
continue;
}
@ -345,7 +333,7 @@ export const sessionSlice = createSlice({
!(!lastMessage.toolCalls?.length && !lastMessage.content) &&
// And there's a difference in tool call presence
(lastMessage.toolCalls?.length ?? 0) !==
(message.toolCalls?.length ?? 0))
(message.toolCalls?.length ?? 0))
) {
// Create a new message
const historyItem: ChatHistoryItemWithMessageId = {
@ -495,9 +483,9 @@ export const sessionSlice = createSlice({
state.allSessionMetadata = state.allSessionMetadata.map((session) =>
session.sessionId === payload.sessionId
? {
...session,
...payload,
}
...session,
...payload,
}
: session,
);
if (payload.title && payload.sessionId === state.id) {
@ -532,8 +520,9 @@ export const sessionSlice = createSlice({
payload.rangeInFileWithContents.filepath,
);
const lineNums = `(${payload.rangeInFileWithContents.range.start.line + 1
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
const lineNums = `(${
payload.rangeInFileWithContents.range.start.line + 1
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
contextItems.push({
name: `${fileName} ${lineNums}`,
@ -553,34 +542,6 @@ export const sessionSlice = createSlice({
state.history[state.history.length - 1].contextItems = contextItems;
},
// Important: these reducers don't handle selected profile/organization fallback logic
// That is done in thunks
setSelectedProfile: (
state,
{ payload }: PayloadAction<ProfileDescription | null>,
) => {
state.selectedProfile = payload;
},
setAvailableProfiles: (
state,
{ payload }: PayloadAction<ProfileDescription[] | null>,
) => {
state.availableProfiles = payload;
},
setOrganizations: (
state,
{ payload }: PayloadAction<OrganizationDescription[]>,
) => {
state.organizations = payload;
},
setSelectedOrganizationId: (
state,
{ payload }: PayloadAction<string | null>,
) => {
state.selectedOrganizationId = payload;
},
///////////////
updateCurCheckpoint: (
state,
{ payload }: PayloadAction<{ filepath: string; content: string }>,
@ -718,9 +679,9 @@ function addPassthroughCases(
) {
thunks.forEach((thunk) => {
builder
.addCase(thunk.fulfilled, (state, action) => { })
.addCase(thunk.rejected, (state, action) => { })
.addCase(thunk.pending, (state, action) => { });
.addCase(thunk.fulfilled, (state, action) => {})
.addCase(thunk.rejected, (state, action) => {})
.addCase(thunk.pending, (state, action) => {});
});
}
@ -777,11 +738,6 @@ export const {
updateSessionMetadata,
deleteSessionMetadata,
setNewestCodeblocksForInput,
setAvailableProfiles,
setSelectedProfile,
setOrganizations,
setSelectedOrganizationId,
} = sessionSlice.actions;
export const {

View file

@ -13,6 +13,7 @@ import configReducer from "./slices/configSlice";
import editModeStateReducer from "./slices/editModeState";
import indexingReducer from "./slices/indexingSlice";
import miscReducer from "./slices/miscSlice";
import { profilesReducer } from "./slices/profiles";
import sessionReducer from "./slices/sessionSlice";
import tabsReducer from "./slices/tabsSlice";
import uiReducer from "./slices/uiSlice";
@ -30,13 +31,12 @@ const rootReducer = combineReducers({
config: configReducer,
indexing: indexingReducer,
tabs: tabsReducer,
profiles: profilesReducer,
});
const saveSubsetFilters = [
createFilter("session", [
"history",
"selectedOrganizationId",
"selectedProfile",
"id",
"lastSessionId",
"title",
@ -45,10 +45,6 @@ const saveSubsetFilters = [
"mode",
"codeToEdit",
// TODO consider removing persisted profiles/orgs
"availableProfiles",
"organizations",
// higher risk to persist
// codeBlockApplyStates
// symbols
@ -60,6 +56,13 @@ const saveSubsetFilters = [
createFilter("ui", ["toolSettings", "useTools"]),
createFilter("indexing", []),
createFilter("tabs", ["tabs"]),
createFilter("profiles", [
// TODO consider removing persisted profiles/orgs
"availableProfiles",
"organizations",
"selectedOrganizationId",
"selectedProfile",
]),
];
const migrations: MigrationManifest = {