Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add command to show chat session history #180770

Merged
merged 1 commit into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import { localize } from 'vs/nls';
import { Action2, IAction2Options, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ViewAction } from 'vs/workbench/browser/parts/views/viewPane';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { IInteractiveSessionEditorOptions, InteractiveSessionEditor } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionEditor';
import { InteractiveSessionEditorInput } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionEditorInput';
import { InteractiveSessionViewPane } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionViewPane';
import { IInteractiveSessionWidgetService } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionWidget';
import { CONTEXT_IN_INTERACTIVE_INPUT, CONTEXT_IN_INTERACTIVE_SESSION } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveSessionDetail, IInteractiveSessionService } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveSessionWidgetHistoryService } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWidgetHistoryService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';

Expand Down Expand Up @@ -178,7 +179,7 @@ export function getOpenInteractiveSessionEditorAction(id: string, label: string,

async run(accessor: ServicesAccessor) {
const editorService = accessor.get(IEditorService);
await editorService.openEditor({ resource: InteractiveSessionEditorInput.getNewEditorUri(), options: <IInteractiveSessionEditorOptions>{ providerId: id, pinned: true } });
await editorService.openEditor({ resource: InteractiveSessionEditorInput.getNewEditorUri(), options: <IInteractiveSessionEditorOptions>{ target: { providerId: id }, pinned: true } });
}
};
}
Expand Down Expand Up @@ -212,3 +213,47 @@ export function getClearAction(viewId: string, providerId: string) {
}
};
}

const getHistoryInteractiveSessionActionDescriptorForViewTitle = (viewId: string, providerId: string): Readonly<IAction2Options> & { viewId: string } => ({
viewId,
id: `workbench.action.interactiveSession.${providerId}.history`,
title: {
value: localize('interactiveSession.history.label', "Show History"),
original: 'Show History'
},
menu: {
id: MenuId.ViewTitle,
when: ContextKeyExpr.and(ContextKeyExpr.equals('view', viewId), ContextKeyExpr.has('config.interactive.experimental.chatHistory')),
group: 'navigation',
order: 0
},
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.history,
f1: false
});

export function getHistoryAction(viewId: string, providerId: string) {
return class HistoryAction extends ViewAction<InteractiveSessionViewPane> {
constructor() {
super(getHistoryInteractiveSessionActionDescriptorForViewTitle(viewId, providerId));
}

async runInView(accessor: ServicesAccessor, view: InteractiveSessionViewPane) {
const interactiveSessionService = accessor.get(IInteractiveSessionService);
const quickInputService = accessor.get(IQuickInputService);
const editorService = accessor.get(IEditorService);
const items = interactiveSessionService.getHistory();
const picks = items.map(i => (<IQuickPickItem & { interactiveSession: IInteractiveSessionDetail }>{
label: i.title,
interactiveSession: i
}));
const selection = await quickInputService.pick(picks, { placeHolder: localize('interactiveSession.history.pick', "Select a chat session to restore") });
if (selection) {
const sessionId = selection.interactiveSession.sessionId;
await editorService.openEditor({
resource: InteractiveSessionEditorInput.getNewEditorUri(), options: <IInteractiveSessionEditorOptions>{ target: { sessionId }, pinned: true }
});
}
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class InteractiveSessionResolverContribution extends Disposable {
},
{
createEditorInput: ({ resource, options }) => {
return { editor: instantiationService.createInstance(InteractiveSessionEditorInput, resource, options as IInteractiveSessionEditorOptions, undefined), options };
return { editor: instantiationService.createInstance(InteractiveSessionEditorInput, resource, options as IInteractiveSessionEditorOptions), options };
}
}
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { IProductService } from 'vs/platform/product/common/productService';
import { Registry } from 'vs/platform/registry/common/platform';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { IViewContainersRegistry, IViewDescriptor, IViewsRegistry, ViewContainer, ViewContainerLocation, Extensions as ViewExtensions } from 'vs/workbench/common/views';
import { getClearAction, getOpenInteractiveSessionEditorAction } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { getClearAction, getHistoryAction, getOpenInteractiveSessionEditorAction } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { IInteractiveSessionViewOptions, INTERACTIVE_SIDEBAR_PANEL_ID, InteractiveSessionViewPane } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionViewPane';
import { IInteractiveSessionContributionService, IInteractiveSessionProviderContribution, IRawInteractiveSessionProviderContribution } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContributionService';
import * as extensionsRegistry from 'vs/workbench/services/extensions/common/extensionsRegistry';
Expand Down Expand Up @@ -136,7 +136,8 @@ export class InteractiveSessionContributionService implements IInteractiveSessio
}];
Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews(viewDescriptor, viewContainer);

// Clear action in view title
// Actions in view title
const historyAction = registerAction2(getHistoryAction(viewId, providerDescriptor.id));
const clearAction = registerAction2(getClearAction(viewId, providerDescriptor.id));

// "Open Interactive Session Editor" Action
Expand All @@ -147,6 +148,7 @@ export class InteractiveSessionContributionService implements IInteractiveSessio
Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).deregisterViews(viewDescriptor, viewContainer);
Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).deregisterViewContainer(viewContainer);
clearAction.dispose();
historyAction.dispose();
openEditor.dispose();
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ import { InteractiveSessionEditorInput } from 'vs/workbench/contrib/interactiveS
import { IViewState, InteractiveSessionWidget } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionWidget';
import { IInteractiveSessionService } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';
import { DisposableStore } from 'vs/base/common/lifecycle';

export interface IInteractiveSessionEditorOptions extends IEditorOptions {
providerId: string;
target: { sessionId: string } | { providerId: string };
}

export class InteractiveSessionEditor extends EditorPane {
Expand All @@ -39,6 +40,8 @@ export class InteractiveSessionEditor extends EditorPane {
private _memento: Memento | undefined;
private _viewState: IViewState | undefined;

private _modelDisposables = this._register(new DisposableStore());

constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
Expand Down Expand Up @@ -93,18 +96,19 @@ export class InteractiveSessionEditor extends EditorPane {
}

private updateModel(model: IInteractiveSessionModel): void {
this._modelDisposables.clear();

this._memento = new Memento('interactive-session-editor-' + model.sessionId, this.storageService);
this._viewState = this._memento.getMemento(StorageScope.WORKSPACE, StorageTarget.USER) as IViewState;
this.widget.setModel(model, { ...this._viewState });
const listener = model.onDidDispose(() => {
this._modelDisposables.add(model.onDidDispose(() => {
// TODO go back to swapping out the EditorInput when the session is restarted instead of this listener
listener.dispose();
const newModel = this.interactiveSessionService.startSession(model.providerId, CancellationToken.None);
if (newModel) {
(this.input as InteractiveSessionEditorInput).sessionId = newModel.sessionId;
this.updateModel(newModel);
}
});
}));
}

protected override saveState(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export class InteractiveSessionEditorInput extends EditorInput {
static count = 0;

private readonly inputCount: number;
public model: IInteractiveSessionModel | undefined;
public sessionId: string | undefined;
public providerId: string | undefined;

static getNewEditorUri(): URI {
const handle = Math.floor(Math.random() * 1e9);
Expand All @@ -32,7 +34,6 @@ export class InteractiveSessionEditorInput extends EditorInput {
constructor(
readonly resource: URI,
readonly options: IInteractiveSessionEditorOptions,
initialSessionId: string | undefined,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService
) {
super();
Expand All @@ -42,7 +43,8 @@ export class InteractiveSessionEditorInput extends EditorInput {
throw new Error('Invalid interactive session URI');
}

this.sessionId = initialSessionId;
this.sessionId = 'sessionId' in options.target ? options.target.sessionId : undefined;
this.providerId = 'providerId' in options.target ? options.target.providerId : undefined;
this.inputCount = InteractiveSessionEditorInput.count++;
}

Expand All @@ -69,7 +71,7 @@ export class InteractiveSessionEditorInput extends EditorInput {
override async resolve(): Promise<InteractiveSessionEditorModel | null> {
const model = typeof this.sessionId === 'string' ?
this.interactiveSessionService.retrieveSession(this.sessionId) :
this.interactiveSessionService.startSession(this.options.providerId, CancellationToken.None);
this.interactiveSessionService.startSession(this.providerId!, CancellationToken.None);

if (!model) {
return null;
Expand All @@ -79,6 +81,13 @@ export class InteractiveSessionEditorInput extends EditorInput {
this.sessionId = model.sessionId;
return new InteractiveSessionEditorModel(model);
}

override dispose(): void {
super.dispose();
if (this.sessionId) {
this.interactiveSessionService.clearSession(this.sessionId);
}
}
}

export class InteractiveSessionEditorModel extends Disposable implements IEditorModel {
Expand Down Expand Up @@ -142,7 +151,6 @@ export namespace InteractiveSessionUri {
interface ISerializedInteractiveSessionEditorInput {
options: IInteractiveSessionEditorOptions;
resource: URI;
sessionId: string;
}

export class InteractiveSessionEditorInputSerializer implements IEditorSerializer {
Expand All @@ -161,8 +169,7 @@ export class InteractiveSessionEditorInputSerializer implements IEditorSerialize

const obj: ISerializedInteractiveSessionEditorInput = {
options: input.options,
resource: input.resource,
sessionId: input.sessionId
resource: input.resource
};
return JSON.stringify(obj);
}
Expand All @@ -171,7 +178,7 @@ export class InteractiveSessionEditorInputSerializer implements IEditorSerialize
try {
const parsed: ISerializedInteractiveSessionEditorInput = JSON.parse(serializedEditor);
const resource = URI.revive(parsed.resource);
return instantiationService.createInstance(InteractiveSessionEditorInput, resource, parsed.options as IInteractiveSessionEditorOptions, parsed.sessionId);
return instantiationService.createInstance(InteractiveSessionEditorInput, resource, parsed.options as IInteractiveSessionEditorOptions);
} catch (err) {
return undefined;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ export interface IInteractiveSessionModel {
readonly onDidChange: Event<IInteractiveSessionChangeEvent>;
readonly sessionId: string;
readonly providerId: string;
// readonly title: string;
readonly welcomeMessage: IInteractiveSessionWelcomeMessageModel | undefined;
readonly requestInProgress: boolean;
readonly inputPlaceholder?: string;
Expand All @@ -181,6 +182,7 @@ export interface ISerializableInteractiveSessionRequestData {

export interface ISerializableInteractiveSessionData {
sessionId: string;
creationDate: number;
welcomeMessage: (string | IInteractiveSessionReplyFollowup[])[] | undefined;
requests: ISerializableInteractiveSessionRequestData[];
requesterUsername: string;
Expand Down Expand Up @@ -248,6 +250,8 @@ export class InteractiveSessionModel extends Disposable implements IInteractiveS
return !!lastRequest && !!lastRequest.response && !lastRequest.response.isComplete;
}

private _creationDate: number;

constructor(
public readonly providerId: string,
initialData: ISerializableInteractiveSessionData | undefined,
Expand All @@ -257,6 +261,7 @@ export class InteractiveSessionModel extends Disposable implements IInteractiveS
this._sessionId = initialData ? initialData.sessionId : generateUuid();
this._requests = initialData ? this._deserialize(initialData) : [];
this._providerState = initialData ? initialData.providerState : undefined;
this._creationDate = initialData?.creationDate ?? Date.now();
}

private _deserialize(obj: ISerializableInteractiveSessionData): InteractiveRequestModel[] {
Expand Down Expand Up @@ -383,6 +388,7 @@ export class InteractiveSessionModel extends Disposable implements IInteractiveS
toJSON(): ISerializableInteractiveSessionData {
return {
sessionId: this.sessionId,
creationDate: this._creationDate,
requesterUsername: this._session!.requesterUsername,
requesterAvatarIconUri: this._session!.requesterAvatarIconUri,
responderUsername: this._session!.responderUsername,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ export interface IInteractiveSessionCompleteResponse {
errorDetails?: IInteractiveResponseErrorDetails;
}

export interface IInteractiveSessionDetail {
sessionId: string;
title: string;
}

export interface IInteractiveProviderInfo {
id: string;
displayName: string;
Expand All @@ -176,6 +181,7 @@ export interface IInteractiveSessionService {
addInteractiveRequest(context: any): void;
addCompleteRequest(sessionId: string, message: string, response: IInteractiveSessionCompleteResponse): void;
sendInteractiveRequestToProvider(sessionId: string, message: IInteractiveSessionDynamicRequest): void;
getHistory(): IInteractiveSessionDetail[];

onDidPerformUserAction: Event<IInteractiveSessionUserActionEvent>;
notifyUserAction(event: IInteractiveSessionUserActionEvent): void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storag
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { CONTEXT_PROVIDER_EXISTS } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { ISerializableInteractiveSessionData, ISerializableInteractiveSessionsData, InteractiveSessionModel, InteractiveSessionWelcomeMessageModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';
import { IInteractiveProgress, IInteractiveProvider, IInteractiveProviderInfo, IInteractiveSession, IInteractiveSessionCompleteResponse, IInteractiveSessionDynamicRequest, IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand, InteractiveSessionCopyKind, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveProgress, IInteractiveProvider, IInteractiveProviderInfo, IInteractiveSession, IInteractiveSessionCompleteResponse, IInteractiveSessionDetail, IInteractiveSessionDynamicRequest, IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand, InteractiveSessionCopyKind, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';

const serializedInteractiveSessionKey = 'interactive.sessions';
Expand Down Expand Up @@ -143,7 +143,8 @@ export class InteractiveSessionService extends Disposable implements IInteractiv
private saveState(): void {
let allSessions: (InteractiveSessionModel | ISerializableInteractiveSessionData)[] = Array.from(this._sessionModels.values())
.filter(session => session.getRequests().length > 0);
allSessions = allSessions.concat(Object.values(this._persistedSessions));
allSessions = allSessions.concat(
Object.values(this._persistedSessions).filter(session => session.requests.length));
this.trace('onWillSaveState', `Persisting ${allSessions.length} sessions`);

const serialized = JSON.stringify(allSessions);
Expand Down Expand Up @@ -209,6 +210,18 @@ export class InteractiveSessionService extends Disposable implements IInteractiv
}
}

getHistory(): IInteractiveSessionDetail[] {
const sessions = Object.values(this._persistedSessions);
sessions.sort((a, b) => (b.creationDate ?? 0) - (a.creationDate ?? 0));

return sessions.map(item => {
return <IInteractiveSessionDetail>{
sessionId: item.sessionId,
title: item.requests[0]?.message || '',
};
});
}

startSession(providerId: string, token: CancellationToken): InteractiveSessionModel {
this.trace('startSession', `providerId=${providerId}`);
return this._startSession(providerId, undefined, token);
Expand Down Expand Up @@ -473,6 +486,7 @@ export class InteractiveSessionService extends Disposable implements IInteractiv
throw new Error(`Unknown session: ${sessionId}`);
}

this._persistedSessions[sessionId] = model.toJSON();
model.dispose();
this._sessionModels.delete(sessionId);
this._pendingRequests.get(sessionId)?.cancel();
Expand Down