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

Experiment prompt persistence in cell. #208543

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
5 changes: 4 additions & 1 deletion src/vs/workbench/api/browser/mainThreadNotebookKernels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ abstract class MainThreadKernel implements INotebookKernel {
this.label = data.label;
this.description = data.description;
this.detail = data.detail;
this.supportedLanguages = isNonEmptyArray(data.supportedLanguages) ? data.supportedLanguages : _languageService.getRegisteredLanguageIds();
this.supportedLanguages = isNonEmptyArray(data.supportedLanguages) ? [
...data.supportedLanguages,
'prompt-cell'
] : _languageService.getRegisteredLanguageIds();
this.implementsExecutionOrder = data.supportsExecutionOrder ?? false;
this.hasVariableProvider = data.hasVariableProvider ?? false;
this.localResourceRoot = URI.revive(data.extensionLocation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ export class EmptyCellEditorHintContribution extends EmptyTextEditorHintContribu
return false;
}

if (activeCell.language === 'prompt-cell') {
return false;
}

return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,8 @@ export function insertCell(
type: CellKind,
direction: 'above' | 'below' = 'above',
initialText: string = '',
ui: boolean = false
ui: boolean = false,
targetLanguage: string | undefined = undefined
) {
const viewModel = editor.getViewModel() as NotebookViewModel;
const activeKernel = editor.activeKernel;
Expand All @@ -664,34 +665,37 @@ export function insertCell(

const cell = editor.cellAt(index);
const nextIndex = ui ? viewModel.getNextVisibleCellIndex(index) : index + 1;
let language;
if (type === CellKind.Code) {
const supportedLanguages = activeKernel?.supportedLanguages ?? languageService.getRegisteredLanguageIds();
const defaultLanguage = supportedLanguages[0] || PLAINTEXT_LANGUAGE_ID;
if (cell?.cellKind === CellKind.Code) {
language = cell.language;
} else if (cell?.cellKind === CellKind.Markup) {
const nearestCodeCellIndex = viewModel.nearestCodeCellIndex(index);
if (nearestCodeCellIndex > -1) {
language = viewModel.cellAt(nearestCodeCellIndex)!.language;
let language = targetLanguage;

if (language === undefined) {
if (type === CellKind.Code) {
const supportedLanguages = activeKernel?.supportedLanguages ?? languageService.getRegisteredLanguageIds();
const defaultLanguage = supportedLanguages[0] || PLAINTEXT_LANGUAGE_ID;
if (cell?.cellKind === CellKind.Code) {
language = cell.language;
} else if (cell?.cellKind === CellKind.Markup) {
const nearestCodeCellIndex = viewModel.nearestCodeCellIndex(index);
if (nearestCodeCellIndex > -1) {
language = viewModel.cellAt(nearestCodeCellIndex)!.language;
} else {
language = defaultLanguage;
}
} else {
language = defaultLanguage;
if (cell === undefined && direction === 'above') {
// insert cell at the very top
language = viewModel.viewCells.find(cell => cell.cellKind === CellKind.Code)?.language || defaultLanguage;
} else {
language = defaultLanguage;
}
}
} else {
if (cell === undefined && direction === 'above') {
// insert cell at the very top
language = viewModel.viewCells.find(cell => cell.cellKind === CellKind.Code)?.language || defaultLanguage;
} else {

if (!supportedLanguages.includes(language)) {
// the language no longer exists
language = defaultLanguage;
}
} else {
language = 'markdown';
}

if (!supportedLanguages.includes(language)) {
// the language no longer exists
language = defaultLanguage;
}
} else {
language = 'markdown';
}

const insertIndex = cell ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { Codicon } from 'vs/base/common/codicons';
import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { localize, localize2 } from 'vs/nls';
import { CONTEXT_ACCESSIBILITY_MODE_ENABLED } from 'vs/platform/accessibility/common/accessibility';
import { MenuId, MenuRegistry, registerAction2 } from 'vs/platform/actions/common/actions';
Expand All @@ -14,6 +15,7 @@ import { InputFocusedContextKey } from 'vs/platform/contextkey/common/contextkey
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { CTX_INLINE_CHAT_FOCUSED, CTX_INLINE_CHAT_HAS_PROVIDER, CTX_INLINE_CHAT_INNER_CURSOR_FIRST, CTX_INLINE_CHAT_INNER_CURSOR_LAST, CTX_INLINE_CHAT_LAST_RESPONSE_TYPE, CTX_INLINE_CHAT_RESPONSE_TYPES, InlineChatResponseFeedbackKind, InlineChatResponseTypes } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { insertCell } from 'vs/workbench/contrib/notebook/browser/controller/cellOperations';
import { CTX_NOTEBOOK_CELL_CHAT_FOCUSED, CTX_NOTEBOOK_CHAT_HAS_ACTIVE_REQUEST, CTX_NOTEBOOK_CHAT_OUTER_FOCUS_POSITION, CTX_NOTEBOOK_CHAT_USER_DID_EDIT, MENU_CELL_CHAT_INPUT, MENU_CELL_CHAT_WIDGET, MENU_CELL_CHAT_WIDGET_FEEDBACK, MENU_CELL_CHAT_WIDGET_STATUS } from 'vs/workbench/contrib/notebook/browser/controller/chat/notebookChatContext';
import { NotebookChatController } from 'vs/workbench/contrib/notebook/browser/controller/chat/notebookChatController';
import { CELL_TITLE_CELL_GROUP_ID, INotebookActionContext, INotebookCellActionContext, NotebookAction, NotebookCellAction, getEditorFromArgsOrActivePane } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
Expand Down Expand Up @@ -455,8 +457,10 @@ registerAction2(class extends NotebookAction {

async runWithContext(accessor: ServicesAccessor, context: IInsertCellWithChatArgs) {
const index = Math.max(0, context.cell ? context.notebookEditor.getCellIndex(context.cell) + 1 : 0);
context.notebookEditor.focusContainer();
NotebookChatController.get(context.notebookEditor)?.run(index, context.input, context.autoSend);
// context.notebookEditor.focusContainer();
// NotebookChatController.get(context.notebookEditor)?.run(index, context.input, context.autoSend);
const languageService = accessor.get(ILanguageService);
insertCell(languageService, context.notebookEditor, index, CellKind.Code, 'below', '', true, 'prompt-cell');
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,31 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { Disposable } from 'vs/base/common/lifecycle';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from 'vs/workbench/common/contributions';
import 'vs/workbench/contrib/notebook/browser/controller/chat/cellChatActions';

class NotebookCellChatbenchContribution extends Disposable implements IWorkbenchContribution {

static readonly ID = 'workbench.contrib.notebookCellChatbenchContribution';

constructor(
@ILanguageService private readonly _languageService: ILanguageService,
) {
super();

this._register(this._languageService.registerLanguage({
id: 'prompt-cell',
extensions: ['.prompt-cell'],
aliases: ['Prompt'],
mimetypes: ['text/prompt-cell']
}));
}
}

registerWorkbenchContribution2(
NotebookCellChatbenchContribution.ID,
NotebookCellChatbenchContribution,
WorkbenchPhase.AfterRestored
);
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@

import { Dimension, IFocusTracker, WindowIntervalTimer, getWindow, scheduleAtNextAnimationFrame, trackFocus } from 'vs/base/browser/dom';
import { CancelablePromise, Queue, createCancelablePromise, disposableTimeout, raceCancellationError } from 'vs/base/common/async';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { LRUCache } from 'vs/base/common/map';
import { Mimes } from 'vs/base/common/mime';
import { Schemas } from 'vs/base/common/network';
import { MovingAverage } from 'vs/base/common/numbers';
import { StopWatch } from 'vs/base/common/stopwatch';
Expand Down Expand Up @@ -47,7 +49,7 @@ import { insertCell, runDeleteAction } from 'vs/workbench/contrib/notebook/brows
import { CTX_NOTEBOOK_CELL_CHAT_FOCUSED, CTX_NOTEBOOK_CHAT_HAS_ACTIVE_REQUEST, CTX_NOTEBOOK_CHAT_OUTER_FOCUS_POSITION, CTX_NOTEBOOK_CHAT_USER_DID_EDIT, MENU_CELL_CHAT_INPUT, MENU_CELL_CHAT_WIDGET, MENU_CELL_CHAT_WIDGET_FEEDBACK, MENU_CELL_CHAT_WIDGET_STATUS } from 'vs/workbench/contrib/notebook/browser/controller/chat/notebookChatContext';
import { ICellViewModel, INotebookEditor, INotebookEditorContribution, INotebookViewZone } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { registerNotebookContribution } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CellEditType, CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookExecutionStateService, NotebookExecutionType } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';

class NotebookChatWidget extends Disposable implements INotebookViewZone {
Expand Down Expand Up @@ -1010,6 +1012,101 @@ export class NotebookChatController extends Disposable implements INotebookEdito
}
}

export class NotebookPromptCellController extends Disposable implements INotebookEditorContribution {
static id: string = 'workbench.notebook.promptCellController';
static counter: number = 0;

public static get(editor: INotebookEditor): NotebookPromptCellController | null {
return editor.getContribution<NotebookPromptCellController>(NotebookPromptCellController.id);
}

private _sessionMap = new Map<string, Session>();

constructor(
private readonly _notebookEditor: INotebookEditor,
@IInlineChatSessionService private readonly _inlineChatSessionService: IInlineChatSessionService,) {
super();
}

async acquireSession(editor: IActiveCodeEditor): Promise<Session | undefined> {
const key = editor.getModel().uri.toString();
if (this._sessionMap.has(key)) {
const session = this._sessionMap.get(key);
return session;
}

const session = await this._inlineChatSessionService.createSession(
editor,
{ editMode: EditMode.Live },
CancellationToken.None
);

if (!session) {
return;
}

this._sessionMap.set(key, session);
return session;
}

async acceptInput(cell: ICellViewModel) {
const key = cell.uri.toString();
const session = this._sessionMap.get(key);
if (!session) {
return;
}

const input = cell.model.getValue();
session.addInput(new SessionPrompt(input, 0, true));

const request: IInlineChatRequest = {
requestId: generateUuid(),
prompt: input,
attempt: session.lastInput?.attempt ?? 0,
selection: { selectionStartLineNumber: 1, selectionStartColumn: 1, positionLineNumber: 1, positionColumn: 1 },
wholeRange: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 },
live: true,
previewDocument: cell.uri,
withIntentDetection: true, // TODO: don't hard code but allow in corresponding UI to run without intent detection?
};
const activeRequestCts = new CancellationTokenSource();
const progress = new AsyncProgress<IInlineChatProgressItem>(async data => {
const index = this._notebookEditor.getCellIndex(cell);
if (data.message && index !== undefined) {
this._notebookEditor.textModel?.applyEdits([
{
editType: CellEditType.Output, index: index, outputs: [
{
outputId: 'append1',
outputs: [{ mime: Mimes.markdown, data: VSBuffer.fromString(data.message) }]
}
]
}
], true, undefined, () => undefined, undefined, false);
}
});

const task = session.provider.provideResponse(session.session, request, progress, activeRequestCts.token);
const reply = await raceCancellationError(Promise.resolve(task), activeRequestCts.token);
if (!reply) {
return;
}
const index = this._notebookEditor.getCellIndex(cell);
if (index !== undefined) {
this._notebookEditor.textModel?.applyEdits([
{
editType: CellEditType.Output, index: index, outputs: [
{
outputId: 'append1',
outputs: [{ mime: Mimes.markdown, data: VSBuffer.fromString(reply.message?.value ?? '') }]
}
]
}
], true, undefined, () => undefined, undefined, false);
}
}
}

export class EditStrategy {
private _editCount: number = 0;

Expand Down Expand Up @@ -1085,3 +1182,4 @@ export class EditStrategy {


registerNotebookContribution(NotebookChatController.id, NotebookChatController);
registerNotebookContribution(NotebookPromptCellController.id, NotebookPromptCellController);
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,8 @@ registerAction2(class ChangeCellLanguageAction extends NotebookCellAction<ICellR

const providerLanguages = new Set([
...languages,
'markdown'
'markdown',
'prompt-cell'
]);

providerLanguages.forEach(languageId => {
Expand Down
10 changes: 10 additions & 0 deletions src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ import { PixelRatio } from 'vs/base/browser/pixelRatio';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { PreventDefaultContextMenuItemsContextKeyName } from 'vs/workbench/contrib/webview/browser/webview.contribution';
import { NotebookAccessibilityProvider } from 'vs/workbench/contrib/notebook/browser/notebookAccessibilityProvider';
import { NotebookPromptCellController } from 'vs/workbench/contrib/notebook/browser/controller/chat/notebookChatController';

const $ = DOM.$;

Expand Down Expand Up @@ -2240,6 +2241,15 @@ export class NotebookEditorWidget extends Disposable implements INotebookEditorD
if (!cells) {
cells = this.viewModel.viewCells;
}

const promptCells = Array.from(cells).filter(cell => cell.language === 'prompt-cell');

if (promptCells.length) {
const promptCell = promptCells[0];
NotebookPromptCellController.get(this)?.acceptInput(promptCell);
return;
}

return this.notebookExecutionService.executeNotebookCells(this.textModel, Array.from(cells).map(c => c.model), this.scopedContextKeyService);
}

Expand Down
Loading
Loading